text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('XTypeGroup', () {
test('toJSON() creates correct map', () {
const List<String> extensions = <String>['txt', 'jpg'];
const List<String> mimeTypes = <String>['text/plain'];
const List<String> uniformTypeIdentifiers = <String>['public.plain-text'];
const List<String> webWildCards = <String>['image/*'];
const String label = 'test group';
const XTypeGroup group = XTypeGroup(
label: label,
extensions: extensions,
mimeTypes: mimeTypes,
uniformTypeIdentifiers: uniformTypeIdentifiers,
webWildCards: webWildCards,
);
final Map<String, dynamic> jsonMap = group.toJSON();
expect(jsonMap['label'], label);
expect(jsonMap['extensions'], extensions);
expect(jsonMap['mimeTypes'], mimeTypes);
expect(jsonMap['uniformTypeIdentifiers'], uniformTypeIdentifiers);
expect(jsonMap['webWildCards'], webWildCards);
// Validate the legacy key for backwards compatibility.
expect(jsonMap['macUTIs'], uniformTypeIdentifiers);
});
test('a wildcard group can be created', () {
const XTypeGroup group = XTypeGroup(
label: 'Any',
);
final Map<String, dynamic> jsonMap = group.toJSON();
expect(jsonMap['extensions'], null);
expect(jsonMap['mimeTypes'], null);
expect(jsonMap['uniformTypeIdentifiers'], null);
expect(jsonMap['webWildCards'], null);
expect(group.allowsAny, true);
});
test('allowsAny treats empty arrays the same as null', () {
const XTypeGroup group = XTypeGroup(
label: 'Any',
extensions: <String>[],
mimeTypes: <String>[],
uniformTypeIdentifiers: <String>[],
webWildCards: <String>[],
);
expect(group.allowsAny, true);
});
test('allowsAny returns false if anything is set', () {
const XTypeGroup extensionOnly =
XTypeGroup(label: 'extensions', extensions: <String>['txt']);
const XTypeGroup mimeOnly =
XTypeGroup(label: 'mime', mimeTypes: <String>['text/plain']);
const XTypeGroup utiOnly = XTypeGroup(
label: 'utis', uniformTypeIdentifiers: <String>['public.text']);
const XTypeGroup webOnly =
XTypeGroup(label: 'web', webWildCards: <String>['.txt']);
expect(extensionOnly.allowsAny, false);
expect(mimeOnly.allowsAny, false);
expect(utiOnly.allowsAny, false);
expect(webOnly.allowsAny, false);
});
group('macUTIs -> uniformTypeIdentifiers transition', () {
test('passing only macUTIs should fill uniformTypeIdentifiers', () {
const List<String> uniformTypeIdentifiers = <String>[
'public.plain-text'
];
const XTypeGroup group = XTypeGroup(
macUTIs: uniformTypeIdentifiers,
);
expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers);
});
test(
'passing only uniformTypeIdentifiers should fill uniformTypeIdentifiers',
() {
const List<String> uniformTypeIdentifiers = <String>[
'public.plain-text'
];
const XTypeGroup group = XTypeGroup(
uniformTypeIdentifiers: uniformTypeIdentifiers,
);
expect(group.uniformTypeIdentifiers, uniformTypeIdentifiers);
});
test('macUTIs getter return macUTIs value passed in constructor', () {
const List<String> uniformTypeIdentifiers = <String>[
'public.plain-text'
];
const XTypeGroup group = XTypeGroup(
macUTIs: uniformTypeIdentifiers,
);
expect(group.macUTIs, uniformTypeIdentifiers);
});
test(
'macUTIs getter returns uniformTypeIdentifiers value passed in constructor',
() {
const List<String> uniformTypeIdentifiers = <String>[
'public.plain-text'
];
const XTypeGroup group = XTypeGroup(
uniformTypeIdentifiers: uniformTypeIdentifiers,
);
expect(group.macUTIs, uniformTypeIdentifiers);
});
test('passing both uniformTypeIdentifiers and macUTIs should throw', () {
expect(
() => XTypeGroup(
macUTIs: const <String>['public.plain-text'],
uniformTypeIdentifiers: const <String>['public.plain-images']),
throwsA(predicate((Object? e) =>
e is AssertionError &&
e.message ==
'Only one of uniformTypeIdentifiers or macUTIs can be non-null')));
});
test(
'having uniformTypeIdentifiers and macUTIs as null should leave uniformTypeIdentifiers as null',
() {
const XTypeGroup group = XTypeGroup();
expect(group.uniformTypeIdentifiers, null);
});
});
test('leading dots are removed from extensions', () {
const List<String> extensions = <String>['.txt', '.jpg'];
const XTypeGroup group = XTypeGroup(extensions: extensions);
expect(group.extensions, <String>['txt', 'jpg']);
});
});
}
| packages/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart/0 | {
"file_path": "packages/packages/file_selector/file_selector_platform_interface/test/x_type_group_test.dart",
"repo_id": "packages",
"token_count": 2132
} | 1,039 |
// 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 "file_selector_plugin.h"
#include <comdef.h>
#include <comip.h>
#include <flutter/flutter_view.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
#include <shobjidl.h>
#include <windows.h>
#include <cassert>
#include <memory>
#include <string>
#include <vector>
#include "file_dialog_controller.h"
#include "string_utils.h"
_COM_SMARTPTR_TYPEDEF(IEnumShellItems, IID_IEnumShellItems);
_COM_SMARTPTR_TYPEDEF(IFileDialog, IID_IFileDialog);
_COM_SMARTPTR_TYPEDEF(IShellItem, IID_IShellItem);
_COM_SMARTPTR_TYPEDEF(IShellItemArray, IID_IShellItemArray);
namespace file_selector_windows {
namespace {
using flutter::CustomEncodableValue;
using flutter::EncodableList;
using flutter::EncodableValue;
// The kind of file dialog to show.
enum class DialogMode { open, save };
// Returns the path for |shell_item| as a UTF-8 string, or an
// empty string on failure.
std::string GetPathForShellItem(IShellItem* shell_item) {
if (shell_item == nullptr) {
return "";
}
wchar_t* wide_path = nullptr;
if (!SUCCEEDED(shell_item->GetDisplayName(SIGDN_FILESYSPATH, &wide_path))) {
return "";
}
std::string path = Utf8FromUtf16(wide_path);
::CoTaskMemFree(wide_path);
return path;
}
// Implementation of FileDialogControllerFactory that makes standard
// FileDialogController instances.
class DefaultFileDialogControllerFactory : public FileDialogControllerFactory {
public:
DefaultFileDialogControllerFactory() {}
virtual ~DefaultFileDialogControllerFactory() {}
// Disallow copy and assign.
DefaultFileDialogControllerFactory(
const DefaultFileDialogControllerFactory&) = delete;
DefaultFileDialogControllerFactory& operator=(
const DefaultFileDialogControllerFactory&) = delete;
std::unique_ptr<FileDialogController> CreateController(
IFileDialog* dialog) const override {
assert(dialog != nullptr);
return std::make_unique<FileDialogController>(dialog);
}
};
// Wraps an IFileDialog, managing object lifetime as a scoped object and
// providing a simplified API for interacting with it as needed for the plugin.
class DialogWrapper {
public:
explicit DialogWrapper(const FileDialogControllerFactory& dialog_factory,
IID type) {
is_open_dialog_ = type == CLSID_FileOpenDialog;
IFileDialogPtr dialog = nullptr;
last_result_ = CoCreateInstance(type, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dialog));
dialog_controller_ = dialog_factory.CreateController(dialog);
}
// Attempts to set the default folder for the dialog to |path|,
// if it exists.
void SetFolder(std::string_view path) {
std::wstring wide_path = Utf16FromUtf8(path);
IShellItemPtr item;
last_result_ = SHCreateItemFromParsingName(wide_path.c_str(), nullptr,
IID_PPV_ARGS(&item));
if (!SUCCEEDED(last_result_)) {
return;
}
dialog_controller_->SetFolder(item);
}
// Sets the file name that is initially shown in the dialog.
void SetFileName(std::string_view name) {
std::wstring wide_name = Utf16FromUtf8(name);
last_result_ = dialog_controller_->SetFileName(wide_name.c_str());
}
// Sets the label of the confirmation button.
void SetOkButtonLabel(std::string_view label) {
std::wstring wide_label = Utf16FromUtf8(label);
last_result_ = dialog_controller_->SetOkButtonLabel(wide_label.c_str());
}
// Adds the given options to the dialog's current option set.
void AddOptions(FILEOPENDIALOGOPTIONS new_options) {
FILEOPENDIALOGOPTIONS options;
last_result_ = dialog_controller_->GetOptions(&options);
if (!SUCCEEDED(last_result_)) {
return;
}
options |= new_options;
if (options & FOS_PICKFOLDERS) {
opening_directory_ = true;
}
last_result_ = dialog_controller_->SetOptions(options);
}
// Sets the filters for allowed file types to select.
void SetFileTypeFilters(const EncodableList& filters) {
const std::wstring spec_delimiter = L";";
const std::wstring file_wildcard = L"*.";
std::vector<COMDLG_FILTERSPEC> filter_specs;
// Temporary ownership of the constructed strings whose data is used in
// filter_specs, so that they live until the call to SetFileTypes is done.
std::vector<std::wstring> filter_names;
std::vector<std::wstring> filter_extensions;
filter_extensions.reserve(filters.size());
filter_names.reserve(filters.size());
for (const EncodableValue& filter_info_value : filters) {
const auto& type_group = std::any_cast<TypeGroup>(
std::get<CustomEncodableValue>(filter_info_value));
filter_names.push_back(Utf16FromUtf8(type_group.label()));
filter_extensions.push_back(L"");
std::wstring& spec = filter_extensions.back();
if (type_group.extensions().empty()) {
spec += L"*.*";
} else {
for (const EncodableValue& extension : type_group.extensions()) {
if (!spec.empty()) {
spec += spec_delimiter;
}
spec +=
file_wildcard + Utf16FromUtf8(std::get<std::string>(extension));
}
}
filter_specs.push_back({filter_names.back().c_str(), spec.c_str()});
}
last_result_ = dialog_controller_->SetFileTypes(
static_cast<UINT>(filter_specs.size()), filter_specs.data());
}
// Displays the dialog, and returns the result, or nullopt on error.
std::optional<FileDialogResult> Show(HWND parent_window) {
assert(dialog_controller_);
last_result_ = dialog_controller_->Show(parent_window);
if (!SUCCEEDED(last_result_)) {
return std::nullopt;
}
EncodableList files;
if (is_open_dialog_) {
IShellItemArrayPtr shell_items;
last_result_ = dialog_controller_->GetResults(&shell_items);
if (!SUCCEEDED(last_result_)) {
return std::nullopt;
}
IEnumShellItemsPtr item_enumerator;
last_result_ = shell_items->EnumItems(&item_enumerator);
if (!SUCCEEDED(last_result_)) {
return std::nullopt;
}
IShellItemPtr shell_item;
while (item_enumerator->Next(1, &shell_item, nullptr) == S_OK) {
files.push_back(EncodableValue(GetPathForShellItem(shell_item)));
}
} else {
IShellItemPtr shell_item;
last_result_ = dialog_controller_->GetResult(&shell_item);
if (!SUCCEEDED(last_result_)) {
return std::nullopt;
}
files.push_back(EncodableValue(GetPathForShellItem(shell_item)));
}
FileDialogResult result(files, nullptr);
UINT file_type_index;
if (SUCCEEDED(dialog_controller_->GetFileTypeIndex(&file_type_index)) &&
file_type_index > 0) {
// Convert from the one-based index to a Dart index.
result.set_type_group_index(file_type_index - 1);
}
return result;
}
// Returns the result of the last Win32 API call related to this object.
HRESULT last_result() { return last_result_; }
private:
// The dialog controller that all interactions are mediated through, to allow
// for unit testing.
std::unique_ptr<FileDialogController> dialog_controller_;
bool is_open_dialog_;
bool opening_directory_ = false;
HRESULT last_result_;
};
ErrorOr<FileDialogResult> ShowDialog(
const FileDialogControllerFactory& dialog_factory, HWND parent_window,
DialogMode mode, const SelectionOptions& options,
const std::string* initial_directory, const std::string* suggested_name,
const std::string* confirm_label) {
IID dialog_type =
mode == DialogMode::save ? CLSID_FileSaveDialog : CLSID_FileOpenDialog;
DialogWrapper dialog(dialog_factory, dialog_type);
if (!SUCCEEDED(dialog.last_result())) {
return FlutterError("System error", "Could not create dialog",
EncodableValue(dialog.last_result()));
}
FILEOPENDIALOGOPTIONS dialog_options = 0;
if (options.select_folders()) {
dialog_options |= FOS_PICKFOLDERS;
}
if (options.allow_multiple()) {
dialog_options |= FOS_ALLOWMULTISELECT;
}
if (dialog_options != 0) {
dialog.AddOptions(dialog_options);
}
if (initial_directory) {
dialog.SetFolder(*initial_directory);
}
if (suggested_name) {
dialog.SetFileName(*suggested_name);
}
if (confirm_label) {
dialog.SetOkButtonLabel(*confirm_label);
}
if (!options.allowed_types().empty()) {
dialog.SetFileTypeFilters(options.allowed_types());
}
std::optional<FileDialogResult> result = dialog.Show(parent_window);
if (!result) {
if (dialog.last_result() != HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
return FlutterError("System error", "Could not show dialog",
EncodableValue(dialog.last_result()));
} else {
return FileDialogResult(EncodableList(), nullptr);
}
}
return std::move(result.value());
}
// Returns the top-level window that owns |view|.
HWND GetRootWindow(flutter::FlutterView* view) {
return ::GetAncestor(view->GetNativeWindow(), GA_ROOT);
}
} // namespace
// static
void FileSelectorPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
std::unique_ptr<FileSelectorPlugin> plugin =
std::make_unique<FileSelectorPlugin>(
[registrar] { return GetRootWindow(registrar->GetView()); },
std::make_unique<DefaultFileDialogControllerFactory>());
FileSelectorApi::SetUp(registrar->messenger(), plugin.get());
registrar->AddPlugin(std::move(plugin));
}
FileSelectorPlugin::FileSelectorPlugin(
FlutterRootWindowProvider window_provider,
std::unique_ptr<FileDialogControllerFactory> dialog_controller_factory)
: get_root_window_(std::move(window_provider)),
controller_factory_(std::move(dialog_controller_factory)) {}
FileSelectorPlugin::~FileSelectorPlugin() = default;
ErrorOr<FileDialogResult> FileSelectorPlugin::ShowOpenDialog(
const SelectionOptions& options, const std::string* initialDirectory,
const std::string* confirmButtonText) {
return ShowDialog(*controller_factory_, get_root_window_(), DialogMode::open,
options, initialDirectory, nullptr, confirmButtonText);
}
ErrorOr<FileDialogResult> FileSelectorPlugin::ShowSaveDialog(
const SelectionOptions& options, const std::string* initialDirectory,
const std::string* suggestedName, const std::string* confirmButtonText) {
return ShowDialog(*controller_factory_, get_root_window_(), DialogMode::save,
options, initialDirectory, suggestedName,
confirmButtonText);
}
} // namespace file_selector_windows
| packages/packages/file_selector/file_selector_windows/windows/file_selector_plugin.cpp/0 | {
"file_path": "packages/packages/file_selector/file_selector_windows/windows/file_selector_plugin.cpp",
"repo_id": "packages",
"token_count": 4004
} | 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.
import 'package:flutter/material.dart';
import 'package:flutter_adaptive_scaffold_example/adaptive_scaffold_demo.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
final Finder body = find.byKey(const Key('body'));
final Finder sBody = find.byKey(const Key('sBody'));
final Finder bnav = find.byKey(const Key('bottomNavigation'));
final Finder pnav = find.byKey(const Key('primaryNavigation'));
final Finder pnav1 = find.byKey(const Key('primaryNavigation1'));
Future<void> updateScreen(double width, WidgetTester tester) async {
await tester.binding.setSurfaceSize(Size(width, 800));
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: MediaQueryData(size: Size(width, 800)),
child: const example.MyHomePage()),
),
);
await tester.pumpAndSettle();
}
testWidgets('dislays correct item of config based on screen width',
(WidgetTester tester) async {
await updateScreen(300, tester);
expect(sBody, findsNothing);
expect(bnav, findsOneWidget);
expect(body, findsNothing);
expect(pnav, findsNothing);
expect(pnav1, findsNothing);
await updateScreen(800, tester);
expect(body, findsOneWidget);
expect(body, findsOneWidget);
expect(bnav, findsNothing);
expect(sBody, findsOneWidget);
expect(pnav, findsOneWidget);
expect(pnav1, findsNothing);
await updateScreen(1100, tester);
expect(body, findsOneWidget);
expect(pnav, findsNothing);
expect(pnav1, findsOneWidget);
});
}
| packages/packages/flutter_adaptive_scaffold/example/test/main_test.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/example/test/main_test.dart",
"repo_id": "packages",
"token_count": 619
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'simulated_layout.dart';
void main() {
testWidgets('Desktop breakpoints do not show on mobile device',
(WidgetTester tester) async {
// Pump a small layout on a mobile device. The small slot
// should give the mobile slot layout, not the desktop layout.
await tester.pumpWidget(SimulatedLayout.small.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.smallMobile')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.smallDesktop')), findsNothing);
// Do the same with a medium layout on a mobile
await tester.pumpWidget(SimulatedLayout.medium.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.mediumMobile')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.mediumDesktop')), findsNothing);
// Large layout on mobile
await tester.pumpWidget(SimulatedLayout.large.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.largeMobile')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.largeDesktop')), findsNothing);
}, variant: TargetPlatformVariant.mobile());
testWidgets('Mobile breakpoints do not show on desktop device',
(WidgetTester tester) async {
// Pump a small layout on a desktop device. The small slot
// should give the mobile slot layout, not the desktop layout.
await tester.pumpWidget(SimulatedLayout.small.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.smallDesktop')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.smallMobile')), findsNothing);
// Do the same with a medium layout on a desktop
await tester.pumpWidget(SimulatedLayout.medium.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.mediumDesktop')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.mediumMobile')), findsNothing);
// Large layout on desktop
await tester.pumpWidget(SimulatedLayout.large.slot(tester));
await tester.pumpAndSettle();
expect(find.byKey(const Key('Breakpoints.largeDesktop')), findsOneWidget);
expect(find.byKey(const Key('Breakpoints.largeMobile')), findsNothing);
}, variant: TargetPlatformVariant.desktop());
}
| packages/packages/flutter_adaptive_scaffold/test/breakpoint_test.dart/0 | {
"file_path": "packages/packages/flutter_adaptive_scaffold/test/breakpoint_test.dart",
"repo_id": "packages",
"token_count": 826
} | 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.
// The code in this file (and all other dart files in the package) is
// analyzed using the rules activated in `analysis_options.yaml`.
// The following syntax deactivates a lint for the entire file:
// ignore_for_file: avoid_renaming_method_parameters
void main() {
const String partOne = 'Hello';
const String partTwo = 'World';
// The following syntax deactivates a lint on a per-line bases:
print('$partOne $partTwo'); // ignore: avoid_print
}
abstract class Base {
int methodA(int foo);
String methodB(String foo);
}
// Normally, the parameter renaming from `foo` to `bar` in this class would
// trigger the `avoid_renaming_method_parameters` lint, but it has been
// deactivated for the file with the `ignore_for_file` comment above.
class Sub extends Base {
@override
int methodA(int bar) => bar;
@override
String methodB(String bar) => bar;
}
| packages/packages/flutter_lints/example/lib/main.dart/0 | {
"file_path": "packages/packages/flutter_lints/example/lib/main.dart",
"repo_id": "packages",
"token_count": 305
} | 1,043 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(goderbauer): Restructure the examples to avoid this ignore, https://github.com/flutter/flutter/issues/110208.
// ignore_for_file: avoid_implementing_value_types
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;
import '../shared/markdown_demo_widget.dart';
// ignore_for_file: public_member_api_docs
// Markdown source data showing the use of subscript tags.
const String _data = '''
## Subscript Syntax
NaOH + Al_2O_3 = NaAlO_2 + H_2O
C_4H_10 = C_2H_6 + C_2H_4
''';
const String _notes = """
# Subscript Syntax Demo
---
## Overview
This is an example of how to create an inline syntax parser with an
associated element builder. This example defines an inline syntax parser that
matches instances of an underscore character "**_**" followed by a integer
numerical value. When the parser finds a match for this syntax sequence,
a '**sub**' element is inserted into the abstract syntac tree. The supplied
builder for the '**sub**' element, SubscriptBuilder, is then called to create
an appropriate RichText widget for the formatted output.
## Usage
To support a new custom inline Markdown tag, an inline syntax object needs to be
defined for the Markdown parser and an element builder which is deligated the
task of building the appropriate Flutter widgets for the resulting Markdown
output. Instances of these objects need to be provided to the Markdown widget.
```
Markdown(
data: _data,
builders: {
'sub': SubscriptBuilder(),
},
extensionSet: md.ExtensionSet([], [SubscriptSyntax()]),
);
```
### Inline Syntax Class
```
class SubscriptSyntax extends md.InlineSyntax {
static final _pattern = r'_([0-9]+)';
SubscriptSyntax() : super(_pattern);
@override
bool onMatch(md.InlineParser parser, Match match) {
parser.addNode(md.Element.text('sub', match[1]));
return true;
}
```
### Markdown Element Builder
```
class SubscriptBuilder extends MarkdownElementBuilder {
static const List<String> _subscripts = [
'β', 'β', 'β', 'β', 'β', 'β
', 'β', 'β', 'β', 'β'
];
@override
Widget visitElementAfter(md.Element element, TextStyle preferredStyle) {
String textContent = element.textContent;
String text = '';
for (int i = 0; i < textContent.length; i++) {
text += _subscripts[int.parse(textContent[i])];
}
return SelectableText.rich(TextSpan(text: text));
}
}
```
""";
/// The subscript syntax demo provides an example of creating an inline syntax
/// object which defines the syntax for the Markdown inline parser and an
/// accompanying Markdown element builder object to handle subscript tags.
class SubscriptSyntaxDemo extends StatelessWidget
implements MarkdownDemoWidget {
const SubscriptSyntaxDemo({super.key});
static const String _title = 'Subscript Syntax Demo';
@override
String get title => SubscriptSyntaxDemo._title;
@override
String get description => 'An example of how to create a custom inline '
'syntax parser and element builder for numerical subscripts.';
@override
Future<String> get data => Future<String>.value(_data);
@override
Future<String> get notes => Future<String>.value(_notes);
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: data,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Markdown(
data: snapshot.data!,
builders: <String, MarkdownElementBuilder>{
'sub': SubscriptBuilder(),
},
extensionSet: md.ExtensionSet(
<md.BlockSyntax>[], <md.InlineSyntax>[SubscriptSyntax()]),
);
} else {
return const CircularProgressIndicator();
}
},
);
}
}
class SubscriptBuilder extends MarkdownElementBuilder {
static const List<String> _subscripts = <String>[
'β',
'β',
'β',
'β',
'β',
'β
',
'β',
'β',
'β',
'β'
];
@override
Widget visitElementAfter(md.Element element, TextStyle? preferredStyle) {
// We don't currently have a way to control the vertical alignment of text spans.
// See https://github.com/flutter/flutter/issues/10906#issuecomment-385723664
final String textContent = element.textContent;
String text = '';
for (int i = 0; i < textContent.length; i++) {
text += _subscripts[int.parse(textContent[i])];
}
return SelectableText.rich(TextSpan(text: text));
}
}
class SubscriptSyntax extends md.InlineSyntax {
SubscriptSyntax() : super(_pattern);
static const String _pattern = r'_([0-9]+)';
@override
bool onMatch(md.InlineParser parser, Match match) {
parser.addNode(md.Element.text('sub', match[1]!));
return true;
}
}
| packages/packages/flutter_markdown/example/lib/demos/subscript_syntax_demo.dart/0 | {
"file_path": "packages/packages/flutter_markdown/example/lib/demos/subscript_syntax_demo.dart",
"repo_id": "packages",
"token_count": 1745
} | 1,044 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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';
// The emphasis and strong emphasis section of the GitHub Flavored Markdown
// specification (https://github.github.com/gfm/#emphasis-and-strong-emphasis)
// is extensive covering over 130 example cases. The tests in this file cover
// all of the GFM tests; example 360 through 490.
void main() => defineTests();
void defineTests() {
group(
'Emphasis',
() {
group(
'Rule 1',
() {
// Rule 1 tests check the single '*' can open emphasis.
testWidgets(
// Example 360 from GFM.
'italic text using asterisk tags',
(WidgetTester tester) async {
const String data = '*foo bar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget =
textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 361 from GFM.
'invalid left-flanking delimiter run because * is followed by whitespace',
(WidgetTester tester) async {
const String data = 'a * foo bar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget =
textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 362 from GFM.
'invalid left-flanking delimiter run because * preceded by alphanumeric followed by punctuation',
(WidgetTester tester) async {
const String data = 'a*"foo bar"*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget =
textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
// NOTE: Example 363 is not included. The test is "Unicode nonbreaking
// spaces count as whitespace, too: '* a *' The Markdown parse sees
// this as a unordered list item." https://github.github.com/gfm/#example-363
testWidgets(
// Example 364 from GFM.
'intraword emphasis with * is permitted alpha characters',
(WidgetTester tester) async {
const String data = 'foo*bar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget =
textFinder.evaluate().first.widget as Text;
expect(textWidget, isNotNull);
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with no emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 365 from GFM.
'intraword emphasis with * is permitted numeric characters',
(WidgetTester tester) async {
const String data = '5*6*78';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget =
textFinder.evaluate().first.widget as Text;
expect(textWidget, isNotNull);
final String text = textWidget.textSpan!.toPlainText();
expect(text, '5678');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is normal text with no emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Third text span is normal text with no emphasis.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
},
);
group('Rule 2', () {
testWidgets(
// Example 366 from GFM.
'italic text using underscore tags',
(WidgetTester tester) async {
const String data = '_foo bar_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 367 from GFM.
'invalid left-flanking delimiter run because _ is followed by whitespace',
(WidgetTester tester) async {
const String data = '_ foo bar_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 368 from GFM.
'invalid left-flanking delimiter run because _ preceded by alphanumeric followed by punctuation',
(WidgetTester tester) async {
const String data = 'a_"foo bar"_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 369 from GFM.
'emphasis with _ is not allowed inside words alpha characters',
(WidgetTester tester) async {
const String data = 'foo_bar_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 370 from GFM.
'emphasis with _ is not allowed inside words numeric characters',
(WidgetTester tester) async {
const String data = '5_6_78';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 371 from GFM.
'emphasis with _ is not allowed inside words unicode characters',
(WidgetTester tester) async {
const String data = 'ΠΏΡΠΈΡΡΠ°Π½ΡΠΌ_ΡΡΡΠ΅ΠΌΡΡΡΡ_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 372 from GFM.
'invalid first delimiter right-flanking followed by second delimiter left-flanking',
(WidgetTester tester) async {
const String data = 'aa_"bb"_cc';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 373 from GFM.
'valid open delimiter left- and right-flanking preceded by punctuation',
(WidgetTester tester) async {
const String data = 'foo-_(bar)_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo-(bar)');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with no emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
});
group('Rule 3', () {
testWidgets(
// Example 374 from GFM.
'invalid emphasis - closing delimiter does not match opening delimiter',
(WidgetTester tester) async {
const String data = '_foo*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 375 from GFM.
'invalid emphasis - closing * is preceded by whitespace',
(WidgetTester tester) async {
const String data = '*foo bar *';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 376 from GFM.
'invalid emphasis - closing * is preceded by newline',
(WidgetTester tester) async {
const String data = '*foo bar\n*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '*foo bar *');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 377 from GFM.
'invalid emphasis - second * is preceded by punctuation followed by alphanumeric',
(WidgetTester tester) async {
const String data = '*(*foo)';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 378 from GFM.
'nested * emphasis',
(WidgetTester tester) async {
const String data = '*(*foo*)*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(foo)');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 379 from GFM.
'intraword emphasis with * is allowed',
(WidgetTester tester) async {
const String data = '*foo*bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is normal text with no emphasis.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 4', () {
testWidgets(
// Example 380 from GFM.
'invalid emphasis because closing _ is preceded by whitespace',
(WidgetTester tester) async {
const String data = '_foo bar _';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 381 from GFM.
'invalid emphasis because second _ is preceded by punctuation and followed by an alphanumeric',
(WidgetTester tester) async {
const String data = '_(_foo)';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 382 from GFM.
'nested _ emphasis',
(WidgetTester tester) async {
const String data = '_(_foo_)_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(foo)');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 383 from GFM.
'intraword emphasis with _ is disallowed - alpha characters',
(WidgetTester tester) async {
const String data = '_foo_bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 384 from GFM.
'intraword emphasis with _ is disallowed - unicode characters',
(WidgetTester tester) async {
const String data = '_ΠΏΡΠΈΡΡΠ°Π½ΡΠΌ_ΡΡΡΠ΅ΠΌΡΡΡΡ';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 385 from GFM.
'intraword emphasis with _ is disallowed - nested emphasis tags',
(WidgetTester tester) async {
const String data = '_foo_bar_baz_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo_bar_baz');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 386 from GFM.
'valid emphasis closing delimiter is both left- and right-flanking followed by punctuation',
(WidgetTester tester) async {
const String data = '_(bar)_.';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(bar).');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is normal text with no emphasis.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 5', () {
testWidgets(
// Example 387 from GFM.
'strong emphasis using ** emphasis tags',
(WidgetTester tester) async {
const String data = '**foo bar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 388 from GFM.
'invalid strong emphasis - opening delimiter followed by whitespace',
(WidgetTester tester) async {
const String data = '** foo bar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 389 from GFM.
'invalid strong emphasis - opening ** is preceded by an alphanumeric and followed by punctuation',
(WidgetTester tester) async {
const String data = 'a**"foo"**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 390 from GFM.
'intraword strong emphasis with ** is permitted',
(WidgetTester tester) async {
const String data = 'foo**bar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with no emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
});
group('Rule 6', () {
testWidgets(
// Example 391 from GFM.
'strong emphasis using __ emphasis tags',
(WidgetTester tester) async {
const String data = '__foo bar__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 392 from GFM.
'invalid strong emphasis - opening delimiter followed by whitespace',
(WidgetTester tester) async {
const String data = '__ foo bar__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 393 from GFM.
'invalid strong emphasis - opening delimiter followed by newline',
(WidgetTester tester) async {
const String data = '__\nfoo bar__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '__ foo bar__');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 394 from GFM.
'invalid strong emphasis - opening __ is preceded by an alphanumeric and followed by punctuation',
(WidgetTester tester) async {
const String data = 'a__"foo"__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 395 from GFM.
'intraword strong emphasis is forbidden with __ - alpha characters',
(WidgetTester tester) async {
const String data = 'foo__bar__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 396 from GFM.
'intraword strong emphasis is forbidden with __ - numeric characters',
(WidgetTester tester) async {
const String data = '5__6__78';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 397 from GFM.
'intraword strong emphasis is forbidden with __ - unicode characters',
(WidgetTester tester) async {
const String data = 'ΠΏΡΠΈΡΡΠ°Π½ΡΠΌ__ΡΡΡΠ΅ΠΌΡΡΡΡ__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 398 from GFM.
'intraword strong emphasis is forbidden with __ - nested strong emphasis',
(WidgetTester tester) async {
const String data = '__foo, __bar__, baz__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo, bar, baz');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 399 from GFM.
'valid strong emphasis because opening delimiter is both left- and right-flanking preceded by punctuation',
(WidgetTester tester) async {
const String data = 'foo-__(bar)__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo-(bar)');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with no emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
});
group('Rule 7', () {
testWidgets(
// Example 400 from GFM.
'invalid strong emphasis - closing delimiter is preceded by whitespace',
(WidgetTester tester) async {
const String data = '**foo bar **';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 401 from GFM.
'invalid strong emphasis - second ** is preceded by punctuation and followed by an alphanumeric',
(WidgetTester tester) async {
const String data = '**(**foo)';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 402 from GFM.
'emphasis with nested strong emphasis',
(WidgetTester tester) async {
const String data = '*(**foo**)*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(foo)');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 403 from GFM.
'strong emphasis with multiple nested emphasis',
(WidgetTester tester) async {
const String data =
'**Gomphocarpus (*Gomphocarpus physocarpus*, syn. *Asclepias physocarpa*)**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text,
'Gomphocarpus (Gomphocarpus physocarpus, syn. Asclepias physocarpa)');
// There should be five spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 5, isTrue);
// First text span has bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has both italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
// Fourth text span has both italic style with bold weight.
final InlineSpan fourthSpan = textSpan.children![3];
expectTextSpanStyle(
fourthSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Fifth text span has bold weight.
final InlineSpan fifthSpan = textSpan.children![4];
expectTextSpanStyle(
fifthSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 404 from GFM.
'strong emphasis with nested emphasis',
(WidgetTester tester) async {
const String data = '**foo "*bar*" foo**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo "bar" foo');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has both italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 405 from GFM.
'intraword strong emphasis',
(WidgetTester tester) async {
const String data = '**foo**bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with strong emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span is normal text with no emphasis.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 8', () {
testWidgets(
// Example 406 from GFM.
'invalid strong emphasis - closing delimiter is preceded by whitespace',
(WidgetTester tester) async {
const String data = '__foo bar __';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 407 from GFM.
'invalid strong emphasis - second __ is preceded by punctuation followed by alphanumeric',
(WidgetTester tester) async {
const String data = '__(__foo)';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 408 from GFM.
'strong emphasis nested in emphasis',
(WidgetTester tester) async {
const String data = '_(__foo__)_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(foo)');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 409 from GFM.
'intraword strong emphasis is forbidden with __ - alpha characters',
(WidgetTester tester) async {
const String data = '__foo__bar';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 410 from GFM.
'intraword strong emphasis is forbidden with __ - unicode characters',
(WidgetTester tester) async {
const String data = '__ΠΏΡΠΈΡΡΠ°Π½ΡΠΌ__ΡΡΡΠ΅ΠΌΡΡΡΡ';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 411 from GFM.
'intraword nested strong emphasis is forbidden with __',
(WidgetTester tester) async {
const String data = '__foo__bar__baz__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo__bar__baz');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 412 from GFM.
'strong emphasis because closing delimiter is both left- and right-flanking is followed by punctuation',
(WidgetTester tester) async {
const String data = '__(bar)__.';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '(bar).');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with strong emphasis.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 9', () {
testWidgets(
// Example 413 from GFM.
'nonempty sequence emphasis span - text followed by link',
(WidgetTester tester) async {
const String data = '*foo [bar](/url)*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is plain text and has italic style with normal weight.
final TextSpan firstSpan = textSpan.children![0] as TextSpan;
expect(firstSpan.recognizer, isNull);
expectTextSpanStyle(
firstSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final TextSpan secondSpan = textSpan.children![1] as TextSpan;
expect(secondSpan.recognizer, isNotNull);
expect(secondSpan.recognizer is GestureRecognizer, isTrue);
expectTextSpanStyle(
secondSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 414 from GFM.
'nonempty sequence emphasis span - two lines of text',
(WidgetTester tester) async {
const String data = '*foo\nbar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 415 from GFM.
'strong emphasis nested inside emphasis - _ delimiter',
(WidgetTester tester) async {
const String data = '_foo __bar__ baz_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 416 from GFM.
'emphasis nested inside emphasis',
(WidgetTester tester) async {
const String data = '_foo _bar_ baz_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 417 from GFM.
'intraword emphasis nested inside emphasis - _ delimiter',
(WidgetTester tester) async {
const String data = '__foo_ bar_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 418 from GFM.
'intraword emphasis nested inside emphasis - * delimiter',
(WidgetTester tester) async {
const String data = '*foo *bar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 419 from GFM.
'strong emphasis nested inside emphasis - * delimiter',
(WidgetTester tester) async {
const String data = '*foo **bar** baz*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 418 from GFM.
'intraword strong emphasis nested inside emphasis - * delimiter',
(WidgetTester tester) async {
const String data = '*foo**bar**baz*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobarbaz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 421 from GFM.
'consecutive emphasis sections are not allowed',
(WidgetTester tester) async {
const String data = '*foo**bar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo**bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 422 from GFM.
'strong emphasis nested inside emphasis - space after first word',
(WidgetTester tester) async {
const String data = '***foo** bar*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 423 from GFM.
'strong emphasis nested inside emphasis - space before second word',
(WidgetTester tester) async {
const String data = '*foo **bar***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
testWidgets(
// Example 424 from GFM.
'intraword strong emphasis nested inside emphasis',
(WidgetTester tester) async {
const String data = '*foo**bar***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
testWidgets(
// Example 425 from GFM.
'intraword emphasis and strong emphasis',
(WidgetTester tester) async {
const String data = 'foo***bar***baz';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobarbaz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is plain text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span is plain text with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 426 from GFM.
'intraword emphasis and strong emphasis - multiples of 3',
(WidgetTester tester) async {
const String data = 'foo******bar*********baz';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobar***baz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is plain text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is plain text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
// Third text span is plain text with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 427 from GFM.
'infinite levels of nesting are possible within emphasis',
(WidgetTester tester) async {
const String data = '*foo **bar *baz*\nbim** bop*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz bim bop');
// There should be five spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length, 3);
// First text span has italic style and normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has both italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 428 from GFM.
'infinite levels of nesting are possible within emphasis - text and a link',
(WidgetTester tester) async {
const String data = '*foo [*bar*](/url)*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style and normal weight.
final TextSpan firstSpan = textSpan.children![0] as TextSpan;
expect(firstSpan.recognizer, isNull);
expectTextSpanStyle(
firstSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final TextSpan secondSpan = textSpan.children![1] as TextSpan;
expect(secondSpan.recognizer, isNotNull);
expect(secondSpan.recognizer is GestureRecognizer, isTrue);
expectTextSpanStyle(
secondSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 429 from GFM.
'there can be no empty emphasis * delimiter',
(WidgetTester tester) async {
const String data = '** is not an empty emphasis';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 430 from GFM.
'there can be no empty strong emphasis * delimiter',
(WidgetTester tester) async {
const String data = '**** is not an empty strong emphasis';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 10', () {
testWidgets(
// Example 431 from GFM.
'nonempty sequence of inline elements with strong emphasis - text and a link',
(WidgetTester tester) async {
const String data = '**foo [bar](/url)**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with bold weight.
final TextSpan firstSpan = textSpan.children![0] as TextSpan;
expect(firstSpan.recognizer, isNull);
expectTextSpanStyle(
firstSpan,
null,
FontWeight.bold,
);
// Second span is a link with bold weight.
final TextSpan secondSpan = textSpan.children![1] as TextSpan;
expect(secondSpan.recognizer, isNotNull);
expect(secondSpan.recognizer is GestureRecognizer, isTrue);
expectTextSpanStyle(
secondSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 432 from GFM.
'nonempty sequence of inline elements with strong emphasis - two lines of texts',
(WidgetTester tester) async {
const String data = '**foo\nbar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 433 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested emphasis',
(WidgetTester tester) async {
const String data = '__foo _bar_ baz__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is plain text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span is plain text with bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 434 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested strong emphasis',
(WidgetTester tester) async {
const String data = '__foo __bar__ baz__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 435 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested strong emphasis',
(WidgetTester tester) async {
const String data = '____foo__ bar__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 436 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested strong emphasis',
(WidgetTester tester) async {
const String data = '**foo **bar****';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 437 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested emphasis',
(WidgetTester tester) async {
const String data = '**foo *bar* baz**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is plain text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span is plain text with bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 438 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - intraword nested emphasis',
(WidgetTester tester) async {
const String data = '**foo*bar*baz**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foobarbaz');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span is plain text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span is plain text with bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 439 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested emphasis on first word',
(WidgetTester tester) async {
const String data = '***foo* bar**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Second span is plain text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 440 from GFM.
'emphasis and strong emphasis nested inside strong emphasis - nested emphasis on second word',
(WidgetTester tester) async {
const String data = '**foo *bar***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is plain text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
testWidgets(
// Example 441 from GFM.
'infinite levels of nesting are possible within strong emphasis',
(WidgetTester tester) async {
const String data = '**foo *bar **baz**\nbim* bop**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar baz bim bop');
// There should be five spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length, 3);
// First text span is plain text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span has both italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has both italic style with bold weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 442 from GFM.
'infinite levels of nesting are possible within strong emphasis - text and a link',
(WidgetTester tester) async {
const String data = '**foo [*bar*](/url)**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is plain text and bold weight.
final TextSpan firstSpan = textSpan.children![0] as TextSpan;
expect(firstSpan.recognizer, isNull);
expectTextSpanStyle(
firstSpan,
null,
FontWeight.bold,
);
// Second span has both italic style with normal weight.
final TextSpan secondSpan = textSpan.children![1] as TextSpan;
expect(secondSpan.recognizer, isNotNull);
expect(secondSpan.recognizer is GestureRecognizer, isTrue);
expectTextSpanStyle(
secondSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
testWidgets(
// Example 443 from GFM.
'there can be no empty emphasis _ delimiter',
(WidgetTester tester) async {
const String data = '__ is not an empty emphasis';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 444 from GFM.
'there can be no empty strong emphasis _ delimiter',
(WidgetTester tester) async {
const String data = '____ is not an empty strong emphasis';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 11', () {
testWidgets(
// Example 445 from GFM.
'an * cannot occur at the beginning or end of * delimited emphasis',
(WidgetTester tester) async {
const String data = 'foo ***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 446 from GFM.
'an escaped * can occur inside * delimited emphasis',
(WidgetTester tester) async {
const String data = r'foo *\**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo *');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 446 from GFM.
'an _ can occur inside * delimited emphasis',
(WidgetTester tester) async {
const String data = 'foo *_*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo _');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 448 from GFM.
'an * cannot occur at the beginning or end of ** delimited strong emphasis',
(WidgetTester tester) async {
const String data = 'foo *****';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 449 from GFM.
'an escaped * can occur inside ** delimited strong emphasis',
(WidgetTester tester) async {
const String data = r'foo **\***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo *');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 450 from GFM.
'an _ can occur inside ** delimited strong emphasis',
(WidgetTester tester) async {
const String data = 'foo **_**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo _');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 451 from GFM.
'unmatched emphasis delimiters excess * at beginning',
(WidgetTester tester) async {
const String data = '**foo*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '*foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 452 from GFM.
'unmatched emphasis delimiters excess * at end',
(WidgetTester tester) async {
const String data = '*foo**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo*');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is normal text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 453 from GFM.
'unmatched strong emphasis delimiters excess * at beginning',
(WidgetTester tester) async {
const String data = '***foo**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '*foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 454 from GFM.
'unmatched strong emphasis delimiters excess * at beginning',
(WidgetTester tester) async {
const String data = '****foo*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '***foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 455 from GFM.
'unmatched strong emphasis delimiters excess * at end',
(WidgetTester tester) async {
const String data = '**foo***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo*');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span is plain text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 456 from GFM.
'unmatched strong emphasis delimiters excess * at end',
(WidgetTester tester) async {
const String data = '*foo****';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo***');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is plain text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 12', () {
testWidgets(
// Example 457 from GFM.
'an _ cannot occur at the beginning or end of _ delimited emphasis',
(WidgetTester tester) async {
const String data = 'foo ___';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 458 from GFM.
'an escaped _ can occur inside _ delimited emphasis',
(WidgetTester tester) async {
const String data = r'foo _\__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo _');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 459 from GFM.
'an * can occur inside _ delimited emphasis',
(WidgetTester tester) async {
const String data = 'foo _*_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo *');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 460 from GFM.
'an _ cannot occur at the beginning or end of __ delimited strong emphasis',
(WidgetTester tester) async {
const String data = 'foo _____';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, data);
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 461 from GFM.
'an escaped _ can occur inside __ delimited strong emphasis',
(WidgetTester tester) async {
const String data = r'foo __\___';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo _');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 462 from GFM.
'an * can occur inside __ delimited strong emphasis',
(WidgetTester tester) async {
const String data = 'foo __*__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo *');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 463 from GFM.
'unmatched emphasis delimiters excess _ at beginning',
(WidgetTester tester) async {
const String data = '__foo_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '_foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 464 from GFM.
'unmatched emphasis delimiters excess _ at end',
(WidgetTester tester) async {
const String data = '_foo__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo_');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is normal text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 465 from GFM.
'unmatched strong emphasis delimiters excess _ at beginning',
(WidgetTester tester) async {
const String data = '___foo__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '_foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is normal text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 466 from GFM.
'unmatched strong emphasis delimiters excess _ at beginning',
(WidgetTester tester) async {
const String data = '____foo_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '___foo');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 467 from GFM.
'unmatched strong emphasis delimiters excess _ at end',
(WidgetTester tester) async {
const String data = '__foo___';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo_');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is normal text with bold weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.bold,
);
// Second span is plain text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 468 from GFM.
'unmatched strong emphasis delimiters excess _ at end',
(WidgetTester tester) async {
const String data = '_foo____';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
// Expect text to be unchanged from original data string.
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo___');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is plain text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
});
group('Rule 13', () {
testWidgets(
// Example 469 from GFM.
'nested delimiters must be different - nested * is strong emphasis',
(WidgetTester tester) async {
const String data = '**foo**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 470 from GFM.
'nested delimiters must be different - nest _ in * emphasis',
(WidgetTester tester) async {
const String data = '*_foo_*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 471 from GFM.
'nested delimiters must be different - nested _ is strong emphasis',
(WidgetTester tester) async {
const String data = '__foo__';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 472 from GFM.
'nested delimiters must be different - nest * in _ emphasis',
(WidgetTester tester) async {
const String data = '_*foo*_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
testWidgets(
// Example 473 from GFM.
'nested delimiters must be different - nested * strong emphasis',
(WidgetTester tester) async {
const String data = '****foo****';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 474 from GFM.
'nested delimiters must be different - nested _ strong emphasis',
(WidgetTester tester) async {
const String data = '____foo____';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 475 from GFM.
'nested delimiters must be different - long sequence of * delimiters',
(WidgetTester tester) async {
const String data = '******foo******';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
null,
FontWeight.bold,
);
},
);
});
// Rule 14 doesn't make any difference to flutter_markdown but tests for
// rule 14 are included here for completeness.
group('Rule 14', () {
testWidgets(
// Example 476 from GFM.
'font style and weight order * delimiter',
(WidgetTester tester) async {
const String data = '***foo***';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
testWidgets(
// Example 476 from GFM.
'font style and weight order _ delimiter',
(WidgetTester tester) async {
const String data = '_____foo_____';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo');
expectTextSpanStyle(
textWidget.textSpan! as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
},
);
});
group('Rule 15', () {
testWidgets(
// Example 478 from GFM.
'overlapping * and _ emphasis delimiters',
(WidgetTester tester) async {
const String data = '*foo _bar* baz_';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo _bar baz_');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span is plain text with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.normal,
);
},
);
testWidgets(
// Example 479 from GFM.
'overlapping * and __ emphasis delimiters',
(WidgetTester tester) async {
const String data = '*foo __bar *baz bim__ bam*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, 'foo bar *baz bim bam');
// There should be three spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 3, isTrue);
// First text span has italic style with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
// Second span has italic style with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.bold,
);
// Third text span has italic style with normal weight.
final InlineSpan thirdSpan = textSpan.children![2];
expectTextSpanStyle(
thirdSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
});
group('Rule 16', () {
testWidgets(
// Example 480 from GFM.
'overlapping ** strong emphasis delimiters',
(WidgetTester tester) async {
const String data = '**foo **bar baz**';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '**foo bar baz');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is plain text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span is plain text with bold weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
null,
FontWeight.bold,
);
},
);
testWidgets(
// Example 479 from GFM.
'overlapping * emphasis delimiters',
(WidgetTester tester) async {
const String data = '*foo *bar baz*';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Finder textFinder = find.byType(Text);
expect(textFinder, findsOneWidget);
final Text textWidget = textFinder.evaluate().first.widget as Text;
final String text = textWidget.textSpan!.toPlainText();
expect(text, '*foo bar baz');
// There should be two spans of text.
final TextSpan textSpan = textWidget.textSpan! as TextSpan;
expect(textSpan, isNotNull);
expect(textSpan.children!.length == 2, isTrue);
// First text span is plain text with normal weight.
final InlineSpan firstSpan = textSpan.children![0];
expectTextSpanStyle(
firstSpan as TextSpan,
null,
FontWeight.normal,
);
// Second span has italic style with normal weight.
final InlineSpan secondSpan = textSpan.children![1];
expectTextSpanStyle(
secondSpan as TextSpan,
FontStyle.italic,
FontWeight.normal,
);
},
);
});
group('Rule 17', () {
// The markdown package does not follow rule 17. Sam Rawlins made the
// following comment on issue #280 on March 7, 2020:
//
// In terms of the spec, we are not following Rule 17 of "Emphasis and
// strong emphasis." Inline code spans, links, images, and HTML tags
// group more tightly than emphasis. Currently the Dart package respects
// the broader rule that any time we can close a tag, we do, attempting
// in the order of most recent openings first. I don't think this is
// terribly hard to correct.
// https://github.com/dart-lang/markdown/issues/280
//
// Test for rule 17 are not included since markdown package is not
// following the rule.
}, skip: 'No Rule 17 tests implemented');
},
);
}
| packages/packages/flutter_markdown/test/emphasis_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/emphasis_test.dart",
"repo_id": "packages",
"token_count": 73591
} | 1,045 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils.dart';
void main() => defineTests();
void defineTests() {
group('Table', () {
testWidgets(
'should show properly',
(WidgetTester tester) async {
const String data = '|Header 1|Header 2|\n|-----|-----|\n|Col 1|Col 2|';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
expectTextStrings(
widgets, <String>['Header 1', 'Header 2', 'Col 1', 'Col 2']);
},
);
testWidgets(
'work without the outer pipes',
(WidgetTester tester) async {
const String data = 'Header 1|Header 2\n-----|-----\nCol 1|Col 2';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
expectTextStrings(
widgets, <String>['Header 1', 'Header 2', 'Col 1', 'Col 2']);
},
);
testWidgets(
'should work with alignments',
(WidgetTester tester) async {
const String data =
'|Header 1|Header 2|\n|:----:|----:|\n|Col 1|Col 2|';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Iterable<DefaultTextStyle> styles =
tester.widgetList(find.byType(DefaultTextStyle));
expect(styles.first.textAlign, TextAlign.center);
expect(styles.last.textAlign, TextAlign.right);
},
);
testWidgets(
'should work with styling',
(WidgetTester tester) async {
const String data = '|Header|\n|----|\n|*italic*|';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Iterable<Widget> widgets = tester.allWidgets;
final Text text =
widgets.lastWhere((Widget widget) => widget is Text) as Text;
expectTextStrings(widgets, <String>['Header', 'italic']);
expect(text.textSpan!.style!.fontStyle, FontStyle.italic);
},
);
testWidgets(
'should work next to other tables',
(WidgetTester tester) async {
const String data = '|first header|\n|----|\n|first col|\n\n'
'|second header|\n|----|\n|second col|';
await tester.pumpWidget(
boilerplate(
const MarkdownBody(data: data),
),
);
final Iterable<Widget> tables = tester.widgetList(find.byType(Table));
expect(tables.length, 2);
},
);
testWidgets(
'column width should follow stylesheet',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '|Header|\n|----|\n|Column|';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
'table cell vertical alignment should default to middle',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '|Header|\n|----|\n|Column|';
final MarkdownStyleSheet style = MarkdownStyleSheet.fromTheme(theme);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expect(
table.defaultVerticalAlignment, TableCellVerticalAlignment.middle);
},
);
testWidgets(
'table cell vertical alignment should follow stylesheet',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '|Header|\n|----|\n|Column|';
const TableCellVerticalAlignment tableCellVerticalAlignment =
TableCellVerticalAlignment.top;
final MarkdownStyleSheet style = MarkdownStyleSheet.fromTheme(theme)
.copyWith(tableVerticalAlignment: tableCellVerticalAlignment);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expect(table.defaultVerticalAlignment, tableCellVerticalAlignment);
},
);
testWidgets(
'table cell vertical alignment should follow stylesheet for different values',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '|Header|\n|----|\n|Column|';
const TableCellVerticalAlignment tableCellVerticalAlignment =
TableCellVerticalAlignment.bottom;
final MarkdownStyleSheet style = MarkdownStyleSheet.fromTheme(theme)
.copyWith(tableVerticalAlignment: tableCellVerticalAlignment);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expect(table.defaultVerticalAlignment, tableCellVerticalAlignment);
},
);
testWidgets(
'table with last row of empty table cells',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '|Header 1|Header 2|\n|----|----|\n| | |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(2, 2);
expect(find.byType(Text), findsNWidgets(4));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'Header 1');
expect(cellText[1], 'Header 2');
expect(cellText[2], '');
expect(cellText[3], '');
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
'table with an empty row an last row has an empty table cell',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data =
'|Header 1|Header 2|\n|----|----|\n| | |\n| bar | |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(3, 2);
expect(find.byType(RichText), findsNWidgets(6));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text richText) => richText.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'Header 1');
expect(cellText[1], 'Header 2');
expect(cellText[2], '');
expect(cellText[3], '');
expect(cellText[4], 'bar');
expect(cellText[5], '');
expect(table.defaultColumnWidth, columnWidth);
},
);
group('GFM Examples', () {
testWidgets(
// Example 198 from GFM.
'simple table',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '| foo | bar |\n| --- | --- |\n| baz | bim |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(2, 2);
expect(find.byType(Text), findsNWidgets(4));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'foo');
expect(cellText[1], 'bar');
expect(cellText[2], 'baz');
expect(cellText[3], 'bim');
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
// Example 199 from GFM.
'input table cell data does not need to match column length',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '| abc | defghi |\n:-: | -----------:\nbar | baz';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(2, 2);
expect(find.byType(Text), findsNWidgets(4));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'abc');
expect(cellText[1], 'defghi');
expect(cellText[2], 'bar');
expect(cellText[3], 'baz');
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
// Example 200 from GFM.
'include a pipe in table cell data by escaping the pipe',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data =
'| f\\|oo |\n| ------ |\n| b \\| az |\n| b **\\|** im |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(1, 3);
expect(find.byType(Text), findsNWidgets(4));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'f|oo');
expect(cellText[1], 'defghi');
expect(cellText[2], 'b | az');
expect(cellText[3], 'b | im');
expect(table.defaultColumnWidth, columnWidth);
},
// TODO(mjordan56): Remove skip once the issue #340 in the markdown package
// is fixed and released. https://github.com/dart-lang/markdown/issues/340
// This test will need adjusting once issue #340 is fixed.
skip: true,
);
testWidgets(
// Example 201 from GFM.
'table definition is complete at beginning of new block',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data =
'| abc | def |\n| --- | --- |\n| bar | baz |\n> bar';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(2, 2);
expect(find.byType(Text), findsNWidgets(5));
final List<String?> text = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(text[0], 'abc');
expect(text[1], 'def');
expect(text[2], 'bar');
expect(text[3], 'baz');
expect(table.defaultColumnWidth, columnWidth);
// Blockquote
expect(find.byType(DecoratedBox), findsOneWidget);
expect(text[4], 'bar');
},
);
testWidgets(
// Example 202 from GFM.
'table definition is complete at first empty line',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data =
'| abc | def |\n| --- | --- |\n| bar | baz |\nbar\n\nbar';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(3, 2);
expect(find.byType(Text), findsNWidgets(7));
final List<String?> text = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(text, <String>['abc', 'def', 'bar', 'baz', 'bar', '', 'bar']);
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
// Example 203 from GFM.
'table header row must match the delimiter row in number of cells',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '| abc | def |\n| --- |\n| bar |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
expect(find.byType(Table), findsNothing);
final List<String?> text = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(text[0], '| abc | def | | --- | | bar |');
},
);
testWidgets(
// Example 204 from GFM.
'remainder of table cells may vary, excess cells are ignored',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data =
'| abc | def |\n| --- | --- |\n| bar |\n| bar | baz | boo |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(3, 2);
expect(find.byType(Text), findsNWidgets(6));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText, <String>['abc', 'def', 'bar', '', 'bar', 'baz']);
expect(table.defaultColumnWidth, columnWidth);
},
);
testWidgets(
// Example 205 from GFM.
'no table body is created when no rows are defined',
(WidgetTester tester) async {
final ThemeData theme =
ThemeData.light().copyWith(textTheme: textTheme);
const String data = '| abc | def |\n| --- | --- |';
const FixedColumnWidth columnWidth = FixedColumnWidth(100);
final MarkdownStyleSheet style =
MarkdownStyleSheet.fromTheme(theme).copyWith(
tableColumnWidth: columnWidth,
);
await tester.pumpWidget(
boilerplate(MarkdownBody(data: data, styleSheet: style)));
final Table table = tester.widget(find.byType(Table));
expectTableSize(1, 2);
expect(find.byType(Text), findsNWidgets(2));
final List<String?> cellText = find
.byType(Text)
.evaluate()
.map((Element e) => e.widget)
.cast<Text>()
.map((Text text) => text.textSpan!)
.cast<TextSpan>()
.map((TextSpan e) => e.text)
.toList();
expect(cellText[0], 'abc');
expect(cellText[1], 'def');
expect(table.defaultColumnWidth, columnWidth);
},
);
});
});
}
| packages/packages/flutter_markdown/test/table_test.dart/0 | {
"file_path": "packages/packages/flutter_markdown/test/table_test.dart",
"repo_id": "packages",
"token_count": 9157
} | 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 'dart:async';
import 'dart:io';
import 'file_system.dart';
/// Throw a specialized exception for expected situations
/// where the tool should exit with a clear message to the user
/// and no stack trace unless the --verbose option is specified.
/// For example: network errors.
Never throwToolExit(String? message, {int? exitCode}) {
throw ToolExit(message, exitCode: exitCode);
}
/// Specialized exception for expected situations
/// where the tool should exit with a clear message to the user
/// and no stack trace unless the --verbose option is specified.
/// For example: network errors.
class ToolExit implements Exception {
ToolExit(this.message, {this.exitCode});
final String? message;
final int? exitCode;
@override
String toString() => 'Error: $message';
}
/// Return the name of an enum item.
String getEnumName(dynamic enumItem) {
final String name = '$enumItem';
final int index = name.indexOf('.');
return index == -1 ? name : name.substring(index + 1);
}
/// Runs [fn] with special handling of asynchronous errors.
///
/// If the execution of [fn] does not throw a synchronous exception, and if the
/// [Future] returned by [fn] is completed with a value, then the [Future]
/// returned by [asyncGuard] is completed with that value if it has not already
/// been completed with an error.
///
/// If the execution of [fn] throws a synchronous exception, and no [onError]
/// callback is provided, then the [Future] returned by [asyncGuard] is
/// completed with an error whose object and stack trace are given by the
/// synchronous exception. If an [onError] callback is provided, then the
/// [Future] returned by [asyncGuard] is completed with its result when passed
/// the error object and stack trace.
///
/// If the execution of [fn] results in an asynchronous exception that would
/// otherwise be unhandled, and no [onError] callback is provided, then the
/// [Future] returned by [asyncGuard] is completed with an error whose object
/// and stack trace are given by the asynchronous exception. If an [onError]
/// callback is provided, then the [Future] returned by [asyncGuard] is
/// completed with its result when passed the error object and stack trace.
///
/// After the returned [Future] is completed, whether it be with a value or an
/// error, all further errors resulting from the execution of [fn] are ignored.
///
/// Rationale:
///
/// Consider the following snippet:
/// ```
/// try {
/// await foo();
/// ...
/// } catch (e) {
/// ...
/// }
/// ```
/// If the [Future] returned by `foo` is completed with an error, that error is
/// handled by the catch block. However, if `foo` spawns an asynchronous
/// operation whose errors are unhandled, those errors will not be caught by
/// the catch block, and will instead propagate to the containing [Zone]. This
/// behavior is non-intuitive to programmers expecting the `catch` to catch all
/// the errors resulting from the code under the `try`.
///
/// As such, it would be convenient if the `try {} catch {}` here could handle
/// not only errors completing the awaited [Future]s it contains, but also
/// any otherwise unhandled asynchronous errors occurring as a result of awaited
/// expressions. This is how `await` is often assumed to work, which leads to
/// unexpected unhandled exceptions.
///
/// [asyncGuard] is intended to wrap awaited expressions occurring in a `try`
/// block. The behavior described above gives the behavior that users
/// intuitively expect from `await`. Consider the snippet:
/// ```
/// try {
/// await asyncGuard(() async {
/// var c = Completer();
/// c.completeError('Error');
/// });
/// } catch (e) {
/// // e is 'Error';
/// }
/// ```
/// Without the [asyncGuard] the error 'Error' would be propagated to the
/// error handler of the containing [Zone]. With the [asyncGuard], the error
/// 'Error' is instead caught by the `catch`.
///
/// [asyncGuard] also accepts an [onError] callback for situations in which
/// completing the returned [Future] with an error is not appropriate.
/// For example, it is not always possible to immediately await the returned
/// [Future]. In these cases, an [onError] callback is needed to prevent an
/// error from propagating to the containing [Zone].
///
/// [onError] must have type `FutureOr<T> Function(Object error)` or
/// `FutureOr<T> Function(Object error, StackTrace stackTrace)` otherwise an
/// [ArgumentError] will be thrown synchronously.
Future<T> asyncGuard<T>(
Future<T> Function() fn, {
Function? onError,
}) {
if (onError != null &&
onError is! _UnaryOnError<T> &&
onError is! _BinaryOnError<T>) {
throw ArgumentError('onError must be a unary function accepting an Object, '
'or a binary function accepting an Object and '
'StackTrace. onError must return a T');
}
final Completer<T> completer = Completer<T>();
void handleError(Object e, StackTrace s) {
if (completer.isCompleted) {
return;
}
if (onError == null) {
completer.completeError(e, s);
return;
}
if (onError is _BinaryOnError<T>) {
completer.complete(onError(e, s));
} else if (onError is _UnaryOnError<T>) {
completer.complete(onError(e));
}
}
runZonedGuarded<void>(() async {
try {
final T result = await fn();
if (!completer.isCompleted) {
completer.complete(result);
}
// This catches all exceptions so that they can be propagated to the
// caller-supplied error handling or the completer.
} catch (e, s) {
// ignore: avoid_catches_without_on_clauses, forwards to Future
handleError(e, s);
}
}, (Object e, StackTrace s) {
handleError(e, s);
});
return completer.future;
}
typedef _UnaryOnError<T> = FutureOr<T> Function(Object error);
typedef _BinaryOnError<T> = FutureOr<T> Function(
Object error, StackTrace stackTrace);
/// Whether the test is running in a web browser compiled to JavaScript.
///
/// See also:
///
/// * [kIsWeb], the equivalent constant in the `foundation` library.
const bool isBrowser = identical(0, 0.0);
/// Whether the test is running on the Windows operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the Windows operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isWindows {
if (isBrowser) {
return false;
}
return Platform.isWindows;
}
/// Whether the test is running on the macOS operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the macOS operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isMacOS {
if (isBrowser) {
return false;
}
return Platform.isMacOS;
}
/// Whether the test is running on the Linux operating system.
///
/// This does not include tests compiled to JavaScript running in a browser on
/// the Linux operating system.
///
/// See also:
///
/// * [isBrowser], which reports true for tests running in browsers.
bool get isLinux {
if (isBrowser) {
return false;
}
return Platform.isLinux;
}
String? flutterRoot;
/// Determine the absolute and normalized path for the root of the current
/// Flutter checkout.
///
/// This method has a series of fallbacks for determining the repo location. The
/// first success will immediately return the root without further checks.
///
/// The order of these tests is:
/// 1. FLUTTER_ROOT environment variable contains the path.
/// 2. Platform script is a data URI scheme, returning `../..` to support
/// tests run from `packages/flutter_tools`.
/// 3. Platform script is package URI scheme, returning the grandparent directory
/// of the package config file location from `packages/flutter_tools/.packages`.
/// 4. Platform script file path is the snapshot path generated by `bin/flutter`,
/// returning the grandparent directory from `bin/cache`.
/// 5. Platform script file name is the entrypoint in `packages/flutter_tools/bin/flutter_tools.dart`,
/// returning the 4th parent directory.
/// 6. The current directory
///
/// If an exception is thrown during any of these checks, an error message is
/// printed and `.` is returned by default (6).
String defaultFlutterRoot({
required FileSystem fileSystem,
}) {
const String kFlutterRootEnvironmentVariableName =
'FLUTTER_ROOT'; // should point to //flutter/ (root of flutter/flutter repo)
const String kSnapshotFileName =
'flutter_tools.snapshot'; // in //flutter/bin/cache/
const String kFlutterToolsScriptFileName =
'flutter_tools.dart'; // in //flutter/packages/flutter_tools/bin/
String normalize(String path) {
return fileSystem.path.normalize(fileSystem.path.absolute(path));
}
if (Platform.environment.containsKey(kFlutterRootEnvironmentVariableName)) {
return normalize(
Platform.environment[kFlutterRootEnvironmentVariableName]!);
}
try {
if (Platform.script.scheme == 'data') {
return normalize('../..'); // The tool is running as a test.
}
final String Function(String) dirname = fileSystem.path.dirname;
if (Platform.script.scheme == 'package') {
final String packageConfigPath =
Uri.parse(Platform.packageConfig!).toFilePath(
windows: isWindows,
);
return normalize(dirname(dirname(dirname(packageConfigPath))));
}
if (Platform.script.scheme == 'file') {
final String script = Platform.script.toFilePath(
windows: isWindows,
);
if (fileSystem.path.basename(script) == kSnapshotFileName) {
return normalize(dirname(dirname(fileSystem.path.dirname(script))));
}
if (fileSystem.path.basename(script) == kFlutterToolsScriptFileName) {
return normalize(dirname(dirname(dirname(dirname(script)))));
}
}
} on Exception catch (error) {
// There is currently no logger attached since this is computed at startup.
// ignore: avoid_print
print('$error');
}
return normalize('.');
}
| packages/packages/flutter_migrate/lib/src/base/common.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/base/common.dart",
"repo_id": "packages",
"token_count": 3088
} | 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:yaml/yaml.dart';
import 'base/common.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/project.dart';
/// Represents subdirectories of the flutter project that can be independently created.
///
/// This includes each supported platform as well as a component that represents the
/// root directory of the project.
enum FlutterProjectComponent {
root,
android,
ios,
linux,
macos,
web,
windows,
fuchsia,
}
extension SupportedPlatformExtension on SupportedPlatform {
FlutterProjectComponent toFlutterProjectComponent() {
final String platformName = toString().split('.').last;
return FlutterProjectComponent.values.firstWhere(
(FlutterProjectComponent e) =>
e.toString() == 'FlutterProjectComponent.$platformName');
}
}
extension FlutterProjectComponentExtension on FlutterProjectComponent {
SupportedPlatform? toSupportedPlatform() {
final String platformName = toString().split('.').last;
if (platformName == 'root') {
return null;
}
return SupportedPlatform.values.firstWhere((SupportedPlatform e) =>
e.toString() == 'SupportedPlatform.$platformName');
}
}
enum FlutterProjectType {
/// This is the default project with the user-managed host code.
/// It is different than the "module" template in that it exposes and doesn't
/// manage the platform code.
app,
/// A List/Detail app template that follows community best practices.
skeleton,
/// The is a project that has managed platform host code. It is an application with
/// ephemeral .ios and .android directories that can be updated automatically.
module,
/// This is a Flutter Dart package project. It doesn't have any native
/// components, only Dart.
package,
/// This is a native plugin project.
plugin,
/// This is an FFI native plugin project.
ffiPlugin,
}
String flutterProjectTypeToString(FlutterProjectType? type) {
if (type == null) {
return '';
}
if (type == FlutterProjectType.ffiPlugin) {
return 'plugin_ffi';
}
return getEnumName(type);
}
FlutterProjectType? stringToProjectType(String value) {
FlutterProjectType? result;
for (final FlutterProjectType type in FlutterProjectType.values) {
if (value == flutterProjectTypeToString(type)) {
result = type;
break;
}
}
return result;
}
/// Verifies the expected yaml keys are present in the file.
bool _validateMetadataMap(
YamlMap map, Map<String, Type> validations, Logger logger) {
bool isValid = true;
for (final MapEntry<String, Object> entry in validations.entries) {
if (!map.keys.contains(entry.key)) {
isValid = false;
logger.printTrace('The key `${entry.key}` was not found');
break;
}
final Object? metadataValue = map[entry.key];
if (metadataValue.runtimeType != entry.value) {
isValid = false;
logger.printTrace(
'The value of key `${entry.key}` in .metadata was expected to be ${entry.value} but was ${metadataValue.runtimeType}');
break;
}
}
return isValid;
}
/// A wrapper around the `.metadata` file.
class FlutterProjectMetadata {
/// Creates a MigrateConfig by parsing an existing .migrate_config yaml file.
FlutterProjectMetadata(this.file, Logger logger)
: _logger = logger,
migrateConfig = MigrateConfig() {
if (!file.existsSync()) {
_logger.printTrace('No .metadata file found at ${file.path}.');
// Create a default empty metadata.
return;
}
Object? yamlRoot;
try {
yamlRoot = loadYaml(file.readAsStringSync());
} on YamlException {
// Handled in _validate below.
}
if (yamlRoot is! YamlMap) {
_logger
.printTrace('.metadata file at ${file.path} was empty or malformed.');
return;
}
if (_validateMetadataMap(
yamlRoot, <String, Type>{'version': YamlMap}, _logger)) {
final Object? versionYamlMap = yamlRoot['version'];
if (versionYamlMap is YamlMap &&
_validateMetadataMap(
versionYamlMap,
<String, Type>{
'revision': String,
'channel': String,
},
_logger)) {
_versionRevision = versionYamlMap['revision'] as String?;
_versionChannel = versionYamlMap['channel'] as String?;
}
}
if (_validateMetadataMap(
yamlRoot, <String, Type>{'project_type': String}, _logger)) {
_projectType = stringToProjectType(yamlRoot['project_type'] as String);
}
final Object? migrationYaml = yamlRoot['migration'];
if (migrationYaml is YamlMap) {
migrateConfig.parseYaml(migrationYaml, _logger);
}
}
/// Creates a FlutterProjectMetadata by explicitly providing all values.
FlutterProjectMetadata.explicit({
required this.file,
required String? versionRevision,
required String? versionChannel,
required FlutterProjectType? projectType,
required this.migrateConfig,
required Logger logger,
}) : _logger = logger,
_versionChannel = versionChannel,
_versionRevision = versionRevision,
_projectType = projectType;
/// The name of the config file.
static const String kFileName = '.metadata';
String? _versionRevision;
String? get versionRevision => _versionRevision;
String? _versionChannel;
String? get versionChannel => _versionChannel;
FlutterProjectType? _projectType;
FlutterProjectType? get projectType => _projectType;
/// Metadata and configuration for the migrate command.
MigrateConfig migrateConfig;
final Logger _logger;
final File file;
/// Writes the .migrate_config file in the provided project directory's platform subdirectory.
///
/// We write the file manually instead of with a template because this
/// needs to be able to write the .migrate_config file into legacy apps.
void writeFile({File? outputFile}) {
outputFile = outputFile ?? file;
outputFile
..createSync(recursive: true)
..writeAsStringSync(toString(), flush: true);
}
@override
String toString() {
return '''
# 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: $_versionRevision
channel: $_versionChannel
project_type: ${flutterProjectTypeToString(projectType)}
${migrateConfig.getOutputFileString()}''';
}
void populate({
List<SupportedPlatform>? platforms,
required Directory projectDirectory,
String? currentRevision,
String? createRevision,
bool create = true,
bool update = true,
required Logger logger,
}) {
migrateConfig.populate(
platforms: platforms,
projectDirectory: projectDirectory,
currentRevision: currentRevision,
createRevision: createRevision,
create: create,
update: update,
logger: logger,
);
}
/// Finds the fallback revision to use when no base revision is found in the migrate config.
String getFallbackBaseRevision(Logger logger, String frameworkRevision) {
// Use the .metadata file if it exists.
if (versionRevision != null) {
return versionRevision!;
}
return frameworkRevision;
}
}
/// Represents the migrate command metadata section of a .metadata file.
///
/// This file tracks the flutter sdk git hashes of the last successful migration ('base') and
/// the version the project was created with.
///
/// Each platform tracks a different set of revisions because flutter create can be
/// used to add support for new platforms, so the base and create revision may not always be the same.
class MigrateConfig {
MigrateConfig(
{Map<FlutterProjectComponent, MigratePlatformConfig>? platformConfigs,
this.unmanagedFiles = kDefaultUnmanagedFiles})
: platformConfigs = platformConfigs ??
<FlutterProjectComponent, MigratePlatformConfig>{};
/// A mapping of the files that are unmanaged by defult for each platform.
static const List<String> kDefaultUnmanagedFiles = <String>[
'lib/main.dart',
'ios/Runner.xcodeproj/project.pbxproj',
];
/// The metadata for each platform supported by the project.
final Map<FlutterProjectComponent, MigratePlatformConfig> platformConfigs;
/// A list of paths relative to this file the migrate tool should ignore.
///
/// These files are typically user-owned files that should not be changed.
List<String> unmanagedFiles;
bool get isEmpty =>
platformConfigs.isEmpty &&
(unmanagedFiles.isEmpty || unmanagedFiles == kDefaultUnmanagedFiles);
/// Parses the project for all supported platforms and populates the [MigrateConfig]
/// to reflect the project.
void populate({
List<SupportedPlatform>? platforms,
required Directory projectDirectory,
String? currentRevision,
String? createRevision,
bool create = true,
bool update = true,
required Logger logger,
}) {
final FlutterProject flutterProject = FlutterProject(projectDirectory);
platforms ??= flutterProject.getSupportedPlatforms();
final List<FlutterProjectComponent> components =
<FlutterProjectComponent>[];
for (final SupportedPlatform platform in platforms) {
components.add(platform.toFlutterProjectComponent());
}
components.add(FlutterProjectComponent.root);
for (final FlutterProjectComponent component in components) {
if (platformConfigs.containsKey(component)) {
if (update) {
platformConfigs[component]!.baseRevision = currentRevision;
}
} else {
if (create) {
platformConfigs[component] = MigratePlatformConfig(
component: component,
createRevision: createRevision,
baseRevision: currentRevision);
}
}
}
}
/// Returns the string that should be written to the .metadata file.
String getOutputFileString() {
String unmanagedFilesString = '';
for (final String path in unmanagedFiles) {
unmanagedFilesString += "\n - '$path'";
}
String platformsString = '';
for (final MapEntry<FlutterProjectComponent, MigratePlatformConfig> entry
in platformConfigs.entries) {
platformsString +=
'\n - platform: ${entry.key.toString().split('.').last}\n create_revision: ${entry.value.createRevision == null ? 'null' : "${entry.value.createRevision}"}\n base_revision: ${entry.value.baseRevision == null ? 'null' : "${entry.value.baseRevision}"}';
}
return isEmpty
? ''
: '''
# Tracks metadata for the flutter migrate command
migration:
platforms:$platformsString
# 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:$unmanagedFilesString
''';
}
/// Parses and validates the `migration` section of the .metadata file.
void parseYaml(YamlMap map, Logger logger) {
final Object? platformsYaml = map['platforms'];
if (_validateMetadataMap(
map, <String, Type>{'platforms': YamlList}, logger)) {
if (platformsYaml is YamlList && platformsYaml.isNotEmpty) {
for (final YamlMap platformYamlMap
in platformsYaml.whereType<YamlMap>()) {
if (_validateMetadataMap(
platformYamlMap,
<String, Type>{
'platform': String,
'create_revision': String,
'base_revision': String,
},
logger)) {
final FlutterProjectComponent component = FlutterProjectComponent
.values
.firstWhere((FlutterProjectComponent val) =>
val.toString() ==
'FlutterProjectComponent.${platformYamlMap['platform'] as String}');
platformConfigs[component] = MigratePlatformConfig(
component: component,
createRevision: platformYamlMap['create_revision'] as String?,
baseRevision: platformYamlMap['base_revision'] as String?,
);
} else {
// malformed platform entry
continue;
}
}
}
}
if (_validateMetadataMap(
map, <String, Type>{'unmanaged_files': YamlList}, logger)) {
final Object? unmanagedFilesYaml = map['unmanaged_files'];
if (unmanagedFilesYaml is YamlList && unmanagedFilesYaml.isNotEmpty) {
unmanagedFiles =
List<String>.from(unmanagedFilesYaml.value.cast<String>());
}
}
}
}
/// Holds the revisions for a single platform for use by the flutter migrate command.
class MigratePlatformConfig {
MigratePlatformConfig(
{required this.component, this.createRevision, this.baseRevision});
/// The platform this config describes.
FlutterProjectComponent component;
/// The Flutter SDK revision this platform was created by.
///
/// Null if the initial create git revision is unknown.
final String? createRevision;
/// The Flutter SDK revision this platform was last migrated by.
///
/// Null if the project was never migrated or the revision is unknown.
String? baseRevision;
bool equals(MigratePlatformConfig other) {
return component == other.component &&
createRevision == other.createRevision &&
baseRevision == other.baseRevision;
}
}
| packages/packages/flutter_migrate/lib/src/flutter_project_metadata.dart/0 | {
"file_path": "packages/packages/flutter_migrate/lib/src/flutter_project_metadata.dart",
"repo_id": "packages",
"token_count": 4722
} | 1,048 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/custom_merge.dart';
import 'package:flutter_migrate/src/utils.dart';
import 'src/common.dart';
void main() {
late FileSystem fileSystem;
late BufferLogger logger;
setUpAll(() {
fileSystem = MemoryFileSystem.test();
logger = BufferLogger.test();
});
group('.metadata merge', () {
late MetadataCustomMerge merger;
setUp(() {
merger = MetadataCustomMerge(logger: logger);
});
testWithoutContext('merges empty', () async {
const String current = '';
const String base = '';
const String target = '';
final File currentFile = fileSystem.file('.metadata_current');
final File baseFile = fileSystem.file('.metadata_base');
final File targetFile = fileSystem.file('.metadata_target');
currentFile
..createSync(recursive: true)
..writeAsStringSync(current, flush: true);
baseFile
..createSync(recursive: true)
..writeAsStringSync(base, flush: true);
targetFile
..createSync(recursive: true)
..writeAsStringSync(target, flush: true);
final StringMergeResult result =
merger.merge(currentFile, baseFile, targetFile) as StringMergeResult;
expect(
result.mergedString,
'''
# 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: null
channel: null
project_type: '''
'''
# Tracks metadata for the flutter migrate command
migration:
platforms:
# 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'
''');
});
testWithoutContext('merge adds migration section', () async {
const String current = '''
# my own comment
version:
revision: abcdefg12345
channel: stable
project_type: app
''';
const String base = '''
version:
revision: abcdefg12345base
channel: stable
project_type: app
migration:
platforms:
- platform: root
create_revision: somecreaterevision
base_revision: somebaserevision
- platform: android
create_revision: somecreaterevision
base_revision: somebaserevision
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
''';
const String target = '''
version:
revision: abcdefg12345target
channel: stable
project_type: app
migration:
platforms:
- platform: root
create_revision: somecreaterevision
base_revision: somebaserevision
- platform: android
create_revision: somecreaterevision
base_revision: somebaserevision
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
''';
final File currentFile = fileSystem.file('.metadata_current');
final File baseFile = fileSystem.file('.metadata_base');
final File targetFile = fileSystem.file('.metadata_target');
currentFile
..createSync(recursive: true)
..writeAsStringSync(current, flush: true);
baseFile
..createSync(recursive: true)
..writeAsStringSync(base, flush: true);
targetFile
..createSync(recursive: true)
..writeAsStringSync(target, flush: true);
final StringMergeResult result =
merger.merge(currentFile, baseFile, targetFile) as StringMergeResult;
expect(result.mergedString, '''
# 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: abcdefg12345target
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: somecreaterevision
base_revision: somebaserevision
- platform: android
create_revision: somecreaterevision
base_revision: somebaserevision
# 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'
''');
});
testWithoutContext('merge handles standard migration flow', () async {
const String current = '''
# my own comment
version:
revision: abcdefg12345current
channel: stable
project_type: app
migration:
platforms:
- platform: root
create_revision: somecreaterevisioncurrent
base_revision: somebaserevisioncurrent
- platform: android
create_revision: somecreaterevisioncurrent
base_revision: somebaserevisioncurrent
unmanaged_files:
- 'lib/main.dart'
- 'new/file.dart'
''';
const String base = '''
version:
revision: abcdefg12345base
channel: stable
project_type: app
migration:
platforms:
- platform: root
create_revision: somecreaterevisionbase
base_revision: somebaserevisionbase
- platform: android
create_revision: somecreaterevisionbase
base_revision: somebaserevisionbase
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
''';
const String target = '''
version:
revision: abcdefg12345target
channel: stable
project_type: app
migration:
platforms:
- platform: root
create_revision: somecreaterevisiontarget
base_revision: somebaserevisiontarget
- platform: android
create_revision: somecreaterevisiontarget
base_revision: somebaserevisiontarget
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
- 'extra/file'
''';
final File currentFile = fileSystem.file('.metadata_current');
final File baseFile = fileSystem.file('.metadata_base');
final File targetFile = fileSystem.file('.metadata_target');
currentFile
..createSync(recursive: true)
..writeAsStringSync(current, flush: true);
baseFile
..createSync(recursive: true)
..writeAsStringSync(base, flush: true);
targetFile
..createSync(recursive: true)
..writeAsStringSync(target, flush: true);
final StringMergeResult result =
merger.merge(currentFile, baseFile, targetFile) as StringMergeResult;
expect(result.mergedString, '''
# 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: abcdefg12345target
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: somecreaterevisioncurrent
base_revision: somebaserevisiontarget
- platform: android
create_revision: somecreaterevisioncurrent
base_revision: somebaserevisiontarget
# 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'
- 'new/file.dart'
- 'extra/file'
''');
});
});
}
| packages/packages/flutter_migrate/test/custom_merge_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/custom_merge_test.dart",
"repo_id": "packages",
"token_count": 2775
} | 1,049 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_migrate/src/base/common.dart';
import 'package:flutter_migrate/src/base/file_system.dart';
import 'package:flutter_migrate/src/base/io.dart';
import 'package:flutter_migrate/src/base/logger.dart';
import 'package:flutter_migrate/src/base/signals.dart';
import 'package:flutter_migrate/src/utils.dart';
import 'package:process/process.dart';
import 'src/common.dart';
void main() {
late BufferLogger logger;
late FileSystem fileSystem;
late Directory projectRoot;
late String projectRootPath;
late MigrateUtils utils;
late ProcessManager processManager;
setUpAll(() async {
fileSystem = LocalFileSystem.test(signals: LocalSignals.instance);
logger = BufferLogger.test();
processManager = const LocalProcessManager();
utils = MigrateUtils(
logger: logger,
fileSystem: fileSystem,
processManager: processManager,
);
});
group('git', () {
setUp(() async {
projectRoot = fileSystem.systemTempDirectory
.createTempSync('flutter_migrate_utils_test');
projectRoot.createSync(recursive: true);
projectRootPath = projectRoot.path;
});
tearDown(() async {
tryToDelete(projectRoot);
});
testWithoutContext('init', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
});
testWithoutContext('isGitIgnored', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
projectRoot.childFile('.gitignore')
..createSync()
..writeAsStringSync('ignored_file.dart', flush: true);
expect(
await utils.isGitIgnored('ignored_file.dart', projectRootPath), true);
expect(
await utils.isGitIgnored('other_file.dart', projectRootPath), false);
});
testWithoutContext('isGitRepo', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
expect(await utils.isGitRepo(projectRootPath), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
expect(await utils.isGitRepo(projectRootPath), true);
expect(await utils.isGitRepo(projectRoot.parent.path), false);
});
testWithoutContext('hasUncommittedChanges false on clean repo', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
projectRoot.childFile('.gitignore')
..createSync()
..writeAsStringSync('ignored_file.dart', flush: true);
await Process.run('git', <String>['add', '.'],
workingDirectory: projectRootPath);
await Process.run('git', <String>['commit', '-m', 'Initial commit'],
workingDirectory: projectRootPath);
expect(await utils.hasUncommittedChanges(projectRootPath), false);
});
testWithoutContext('hasUncommittedChanges true on dirty repo', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
projectRoot.childFile('some_file.dart')
..createSync()
..writeAsStringSync('void main() {}', flush: true);
expect(await utils.hasUncommittedChanges(projectRootPath), true);
});
testWithoutContext('logging hasUncommittedChanges true on dirty repo',
() async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
projectRoot.childFile('some_file.dart')
..createSync()
..writeAsStringSync('void main() {}', flush: true);
expect(await hasUncommittedChanges(projectRootPath, logger, utils), true);
});
testWithoutContext('diffFiles', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
final File file1 = projectRoot.childFile('some_file.dart')
..createSync()
..writeAsStringSync('void main() {}\n', flush: true);
final File file2 = projectRoot.childFile('some_other_file.dart');
DiffResult result = await utils.diffFiles(file1, file2);
expect(result.diff, null);
expect(result.diffType, DiffType.deletion);
expect(result.exitCode, null);
result = await utils.diffFiles(file2, file1);
expect(result.diff, null);
expect(result.diffType, DiffType.addition);
expect(result.exitCode, null);
file2.createSync();
file2.writeAsStringSync('void main() {}\n', flush: true);
result = await utils.diffFiles(file1, file2);
expect(result.diff, '');
expect(result.diffType, DiffType.command);
expect(result.exitCode, 0);
file2.writeAsStringSync('void main() {}\na second line\na third line\n',
flush: true);
result = await utils.diffFiles(file1, file2);
expect(
result.diff,
contains(
'@@ -1 +1,3 @@\n void main() {}\n+a second line\n+a third line'));
expect(result.diffType, DiffType.command);
expect(result.exitCode, 1);
});
testWithoutContext('merge', () async {
expect(projectRoot.existsSync(), true);
expect(projectRoot.childDirectory('.git').existsSync(), false);
await utils.gitInit(projectRootPath);
expect(projectRoot.childDirectory('.git').existsSync(), true);
final File file1 = projectRoot.childFile('some_file.dart');
file1.createSync();
file1.writeAsStringSync(
'void main() {}\n\nline1\nline2\nline3\nline4\nline5\n',
flush: true);
final File file2 = projectRoot.childFile('some_other_file.dart');
file2.createSync();
file2.writeAsStringSync(
'void main() {}\n\nline1\nline2\nline3.0\nline3.5\nline4\nline5\n',
flush: true);
final File file3 = projectRoot.childFile('some_other_third_file.dart');
file3.createSync();
file3.writeAsStringSync('void main() {}\n\nline2\nline3\nline4\nline5\n',
flush: true);
StringMergeResult result = await utils.gitMergeFile(
base: file1.path,
current: file2.path,
target: file3.path,
localPath: 'some_file.dart',
) as StringMergeResult;
expect(result.mergedString,
'void main() {}\n\nline2\nline3.0\nline3.5\nline4\nline5\n');
expect(result.hasConflict, false);
expect(result.exitCode, 0);
file3.writeAsStringSync(
'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n',
flush: true);
result = await utils.gitMergeFile(
base: file1.path,
current: file2.path,
target: file3.path,
localPath: 'some_file.dart',
) as StringMergeResult;
expect(
result.mergedString, contains('line3.0\n=======\nline3.1\n>>>>>>>'));
expect(result.hasConflict, true);
expect(result.exitCode, 1);
// Two way merge
result = await utils.gitMergeFile(
base: file1.path,
current: file1.path,
target: file3.path,
localPath: 'some_file.dart',
) as StringMergeResult;
expect(result.mergedString,
'void main() {}\n\nline1\nline2\nline3.1\nline3.5\nline4\nline5\n');
expect(result.hasConflict, false);
expect(result.exitCode, 0);
});
});
testWithoutContext('printCommandText standalone', () async {
printCommandText('test', logger, standalone: false);
expect(logger.statusText, contains('flutter migrate test'));
logger.clear();
printCommandText('rawtext', logger, standalone: null);
expect(logger.statusText, contains('rawtext'));
logger.clear();
printCommandText('fullstandalone', logger);
if (isWindows) {
expect(
logger.statusText,
contains(
r'dart run <flutter_migrate_dir>\bin\flutter_migrate.dart fullstandalone'));
} else {
expect(
logger.statusText,
contains(
'dart run <flutter_migrate_dir>/bin/flutter_migrate.dart fullstandalone'));
}
logger.clear();
});
group('legacy app creation', () {
testWithoutContext('clone and create', () async {
projectRoot =
fileSystem.systemTempDirectory.createTempSync('flutter_sdk_test');
const String revision = '5391447fae6209bb21a89e6a5a6583cac1af9b4b';
expect(await utils.cloneFlutter(revision, projectRoot.path), true);
expect(projectRoot.childFile('README.md').existsSync(), true);
final Directory appDir =
fileSystem.systemTempDirectory.createTempSync('flutter_app');
await utils.createFromTemplates(
projectRoot.childDirectory('bin').path,
name: 'testapp',
androidLanguage: 'java',
iosLanguage: 'objc',
outputDirectory: appDir.path,
);
expect(appDir.childFile('pubspec.yaml').existsSync(), true);
expect(appDir.childFile('.metadata').existsSync(), true);
expect(
appDir.childFile('.metadata').readAsStringSync(), contains(revision));
expect(appDir.childDirectory('android').existsSync(), true);
expect(appDir.childDirectory('ios').existsSync(), true);
expect(appDir.childDirectory('web').existsSync(), false);
projectRoot.deleteSync(recursive: true);
});
},
timeout: const Timeout(Duration(seconds: 500)),
// TODO(stuartmorgan): These should not be unit tests, see
// https://github.com/flutter/flutter/issues/121257.
skip: 'TODO: Speed up, or move to another type of test');
testWithoutContext('conflictsResolved', () async {
expect(utils.conflictsResolved(''), true);
expect(utils.conflictsResolved('hello'), true);
expect(utils.conflictsResolved('hello\n'), true);
expect(
utils.conflictsResolved('hello\nwow a bunch of lines\n\nhi\n'), true);
expect(
utils.conflictsResolved('hello\nwow a bunch of lines\n>>>>>>>\nhi\n'),
false);
expect(
utils.conflictsResolved('hello\nwow a bunch of lines\n=======\nhi\n'),
false);
expect(
utils.conflictsResolved('hello\nwow a bunch of lines\n<<<<<<<\nhi\n'),
false);
expect(
utils.conflictsResolved(
'hello\nwow a bunch of lines\n<<<<<<<\n=======\n<<<<<<<\nhi\n'),
false);
});
}
| packages/packages/flutter_migrate/test/utils_test.dart/0 | {
"file_path": "packages/packages/flutter_migrate/test/utils_test.dart",
"repo_id": "packages",
"token_count": 4494
} | 1,050 |
Instead of using URL strings to navigate, go_router supports
type-safe routes using the go_router_builder package.
To get started, add [go_router_builder][], [build_runner][], and
[build_verify][] to the dev_dependencies section of your pubspec.yaml:
```yaml
dev_dependencies:
go_router_builder: any
build_runner: any
build_verify: any
```
Then extend the [GoRouteData](https://pub.dev/documentation/go_router/latest/go_router/GoRouteData-class.html) class for each route in your app and add the
TypedGoRoute annotation:
```dart
import 'package:go_router/go_router.dart';
part 'go_router_builder.g.dart';
@TypedGoRoute<HomeScreenRoute>(
path: '/',
routes: [
TypedGoRoute<SongRoute>(
path: 'song/:id',
)
]
)
@immutable
class HomeScreenRoute extends GoRouteData {
@override
Widget build(BuildContext context, GoRouterState state) {
return const HomeScreen();
}
}
@immutable
class SongRoute extends GoRouteData {
final int id;
const SongRoute({
required this.id,
});
@override
Widget build(BuildContext context, GoRouterState state) {
return SongScreen(songId: id.toString());
}
}
```
To build the generated files (ending in .g.dart), use the build_runner command:
```
flutter pub global activate build_runner
flutter pub run build_runner build
```
To navigate, construct a GoRouteData object with the required parameters and
call go():
```
TextButton(
onPressed: () {
const SongRoute(id: 2).go(context);
},
child: const Text('Go to song 2'),
),
```
For more information, visit the [go_router_builder
package documentation](https://pub.dev/documentation/go_router_builder/latest/).
[go_router_builder]: https://pub.dev/packages/go_router_builder
[build_runner]: https://pub.dev/packages/build_runner
[build_verify]: https://pub.dev/packages/build_verify | packages/packages/go_router/doc/type-safe-routes.md/0 | {
"file_path": "packages/packages/go_router/doc/type-safe-routes.md",
"repo_id": "packages",
"token_count": 634
} | 1,051 |
// 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 '../data.dart';
/// The book list view.
class BookList extends StatelessWidget {
/// Creates an [BookList].
const BookList({
required this.books,
this.onTap,
super.key,
});
/// The list of books to be displayed.
final List<Book> books;
/// Called when the user taps a book.
final ValueChanged<Book>? onTap;
@override
Widget build(BuildContext context) => ListView.builder(
itemCount: books.length,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(
books[index].title,
),
subtitle: Text(
books[index].author.name,
),
onTap: onTap != null ? () => onTap!(books[index]) : null,
),
);
}
| packages/packages/go_router/example/lib/books/src/widgets/book_list.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/books/src/widgets/book_list.dart",
"repo_id": "packages",
"token_count": 366
} | 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/material.dart';
import 'package:go_router/go_router.dart';
// This scenario demonstrates how to use path parameters and query parameters.
//
// The route segments that start with ':' are treated as path parameters when
// defining GoRoute[s]. The parameter values can be accessed through
// GoRouterState.pathParameters.
//
// The query parameters are automatically stored in GoRouterState.queryParameters.
/// Family data class.
class Family {
/// Create a family.
const Family({required this.name, required this.people});
/// The last name of the family.
final String name;
/// The people in the family.
final Map<String, Person> people;
}
/// Person data class.
class Person {
/// Creates a person.
const Person({required this.name});
/// The first name of the person.
final String name;
}
const Map<String, Family> _families = <String, Family>{
'f1': Family(
name: 'Doe',
people: <String, Person>{
'p1': Person(name: 'Jane'),
'p2': Person(name: 'John'),
},
),
'f2': Family(
name: 'Wong',
people: <String, Person>{
'p1': Person(name: 'June'),
'p2': Person(name: 'Xin'),
},
),
};
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: Query Parameters';
// add the login info into the tree as app state that can change over time
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
title: title,
debugShowCheckedModeBanner: false,
);
late final GoRouter _router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const HomeScreen(),
routes: <GoRoute>[
GoRoute(
name: 'family',
path: 'family/:fid',
builder: (BuildContext context, GoRouterState state) {
return FamilyScreen(
fid: state.pathParameters['fid']!,
asc: state.uri.queryParameters['sort'] == 'asc',
);
}),
],
),
],
);
}
/// The home screen that shows a list of families.
class HomeScreen extends StatelessWidget {
/// Creates a [HomeScreen].
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(App.title),
),
body: ListView(
children: <Widget>[
for (final MapEntry<String, Family> entry in _families.entries)
ListTile(
title: Text(entry.value.name),
onTap: () => context.go('/family/${entry.key}'),
)
],
),
);
}
}
/// The screen that shows a list of persons in a family.
class FamilyScreen extends StatelessWidget {
/// Creates a [FamilyScreen].
const FamilyScreen({required this.fid, required this.asc, super.key});
/// The family to display.
final String fid;
/// Whether to sort the name in ascending order.
final bool asc;
@override
Widget build(BuildContext context) {
final Map<String, String> newQueries;
final List<String> names = _families[fid]!
.people
.values
.map<String>((Person p) => p.name)
.toList();
names.sort();
if (asc) {
newQueries = const <String, String>{'sort': 'desc'};
} else {
newQueries = const <String, String>{'sort': 'asc'};
}
return Scaffold(
appBar: AppBar(
title: Text(_families[fid]!.name),
actions: <Widget>[
IconButton(
onPressed: () => context.goNamed('family',
pathParameters: <String, String>{'fid': fid},
queryParameters: newQueries),
tooltip: 'sort ascending or descending',
icon: const Icon(Icons.sort),
)
],
),
body: ListView(
children: <Widget>[
for (final String name in asc ? names : names.reversed)
ListTile(
title: Text(name),
),
],
),
);
}
}
| packages/packages/go_router/example/lib/path_and_query_parameters.dart/0 | {
"file_path": "packages/packages/go_router/example/lib/path_and_query_parameters.dart",
"repo_id": "packages",
"token_count": 1791
} | 1,053 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
/// Page with custom transition functionality.
///
/// To be used instead of MaterialPage or CupertinoPage, which provide
/// their own transitions.
class CustomTransitionPage<T> extends Page<T> {
/// Constructor for a page with custom transition functionality.
///
/// To be used instead of MaterialPage or CupertinoPage, which provide
/// their own transitions.
const CustomTransitionPage({
required this.child,
required this.transitionsBuilder,
this.transitionDuration = const Duration(milliseconds: 300),
this.reverseTransitionDuration = const Duration(milliseconds: 300),
this.maintainState = true,
this.fullscreenDialog = false,
this.opaque = true,
this.barrierDismissible = false,
this.barrierColor,
this.barrierLabel,
super.key,
super.name,
super.arguments,
super.restorationId,
});
/// The content to be shown in the Route created by this page.
final Widget child;
/// A duration argument to customize the duration of the custom page
/// transition.
///
/// Defaults to 300ms.
final Duration transitionDuration;
/// A duration argument to customize the duration of the custom page
/// transition on pop.
///
/// Defaults to 300ms.
final Duration reverseTransitionDuration;
/// Whether the route should remain in memory when it is inactive.
///
/// If this is true, then the route is maintained, so that any futures it is
/// holding from the next route will properly resolve when the next route
/// pops. If this is not necessary, this can be set to false to allow the
/// framework to entirely discard the route's widget hierarchy when it is
/// not visible.
final bool maintainState;
/// Whether this page route is a full-screen dialog.
///
/// In Material and Cupertino, being fullscreen has the effects of making the
/// app bars have a close button instead of a back button. On iOS, dialogs
/// transitions animate differently and are also not closeable with the
/// back swipe gesture.
final bool fullscreenDialog;
/// Whether the route obscures previous routes when the transition is
/// complete.
///
/// When an opaque route's entrance transition is complete, the routes
/// behind the opaque route will not be built to save resources.
final bool opaque;
/// Whether you can dismiss this route by tapping the modal barrier.
final bool barrierDismissible;
/// The color to use for the modal barrier.
///
/// If this is null, the barrier will be transparent.
final Color? barrierColor;
/// The semantic label used for a dismissible barrier.
///
/// If the barrier is dismissible, this label will be read out if
/// accessibility tools (like VoiceOver on iOS) focus on the barrier.
final String? barrierLabel;
/// Override this method to wrap the child with one or more transition
/// widgets that define how the route arrives on and leaves the screen.
///
/// By default, the child (which contains the widget returned by buildPage) is
/// not wrapped in any transition widgets.
///
/// The transitionsBuilder method, is called each time the Route's state
/// changes while it is visible (e.g. if the value of canPop changes on the
/// active route).
///
/// The transitionsBuilder method is typically used to define transitions
/// that animate the new topmost route's comings and goings. When the
/// Navigator pushes a route on the top of its stack, the new route's
/// primary animation runs from 0.0 to 1.0. When the Navigator pops the
/// topmost route, e.g. because the use pressed the back button, the primary
/// animation runs from 1.0 to 0.0.
final Widget Function(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation, Widget child) transitionsBuilder;
@override
Route<T> createRoute(BuildContext context) =>
_CustomTransitionPageRoute<T>(this);
}
class _CustomTransitionPageRoute<T> extends PageRoute<T> {
_CustomTransitionPageRoute(CustomTransitionPage<T> page)
: super(settings: page);
CustomTransitionPage<T> get _page => settings as CustomTransitionPage<T>;
@override
bool get barrierDismissible => _page.barrierDismissible;
@override
Color? get barrierColor => _page.barrierColor;
@override
String? get barrierLabel => _page.barrierLabel;
@override
Duration get transitionDuration => _page.transitionDuration;
@override
Duration get reverseTransitionDuration => _page.reverseTransitionDuration;
@override
bool get maintainState => _page.maintainState;
@override
bool get fullscreenDialog => _page.fullscreenDialog;
@override
bool get opaque => _page.opaque;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: _page.child,
);
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
_page.transitionsBuilder(
context,
animation,
secondaryAnimation,
child,
);
}
/// Custom transition page with no transition.
class NoTransitionPage<T> extends CustomTransitionPage<T> {
/// Constructor for a page with no transition functionality.
const NoTransitionPage({
required super.child,
super.name,
super.arguments,
super.restorationId,
super.key,
}) : super(
transitionsBuilder: _transitionsBuilder,
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
);
static Widget _transitionsBuilder(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) =>
child;
}
| packages/packages/go_router/lib/src/pages/custom_transition_page.dart/0 | {
"file_path": "packages/packages/go_router/lib/src/pages/custom_transition_page.dart",
"repo_id": "packages",
"token_count": 1787
} | 1,054 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
void main() {
testWidgets('throws if more than one exception handlers are provided.',
(WidgetTester tester) async {
bool thrown = false;
try {
GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (_, GoRouterState state) => const Text('home')),
],
errorBuilder: (_, __) => const Text(''),
onException: (_, __, ___) {},
);
} on Error {
thrown = true;
}
expect(thrown, true);
thrown = false;
try {
GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (_, GoRouterState state) => const Text('home')),
],
errorBuilder: (_, __) => const Text(''),
errorPageBuilder: (_, __) => const MaterialPage<void>(child: Text('')),
);
} on Error {
thrown = true;
}
expect(thrown, true);
thrown = false;
try {
GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (_, GoRouterState state) => const Text('home')),
],
onException: (_, __, ___) {},
errorPageBuilder: (_, __) => const MaterialPage<void>(child: Text('')),
);
} on Error {
thrown = true;
}
expect(thrown, true);
});
group('onException', () {
testWidgets('can redirect.', (WidgetTester tester) async {
final GoRouter router = await createRouter(<RouteBase>[
GoRoute(
path: '/error',
builder: (_, GoRouterState state) =>
Text('redirected ${state.extra}')),
], tester,
onException: (_, GoRouterState state, GoRouter router) =>
router.go('/error', extra: state.uri.toString()));
expect(find.text('redirected /'), findsOneWidget);
router.go('/some-other-location');
await tester.pumpAndSettle();
expect(find.text('redirected /some-other-location'), findsOneWidget);
});
testWidgets('can redirect with extra', (WidgetTester tester) async {
final GoRouter router = await createRouter(<RouteBase>[
GoRoute(
path: '/error',
builder: (_, GoRouterState state) => Text('extra: ${state.extra}')),
], tester,
onException: (_, GoRouterState state, GoRouter router) =>
router.go('/error', extra: state.extra));
expect(find.text('extra: null'), findsOneWidget);
router.go('/some-other-location', extra: 'X');
await tester.pumpAndSettle();
expect(find.text('extra: X'), findsOneWidget);
});
testWidgets('stays on the same page if noop.', (WidgetTester tester) async {
final GoRouter router = await createRouter(
<RouteBase>[
GoRoute(
path: '/',
builder: (_, GoRouterState state) => const Text('home')),
],
tester,
onException: (_, __, ___) {},
);
expect(find.text('home'), findsOneWidget);
router.go('/some-other-location');
await tester.pumpAndSettle();
expect(find.text('home'), findsOneWidget);
});
});
}
| packages/packages/go_router/test/exception_handling_test.dart/0 | {
"file_path": "packages/packages/go_router/test/exception_handling_test.dart",
"repo_id": "packages",
"token_count": 1517
} | 1,055 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router/go_router.dart';
import 'test_helpers.dart';
RouteInformation createRouteInformation(String location, [Object? extra]) {
return RouteInformation(
uri: Uri.parse(location),
state:
RouteInformationState<void>(type: NavigatingType.go, extra: extra));
}
void main() {
Future<GoRouteInformationParser> createParser(
WidgetTester tester, {
required List<RouteBase> routes,
int redirectLimit = 5,
GoRouterRedirect? redirect,
}) async {
final GoRouter router = GoRouter(
routes: routes,
redirectLimit: redirectLimit,
redirect: redirect,
);
addTearDown(router.dispose);
await tester.pumpWidget(MaterialApp.router(
routerConfig: router,
));
return router.routeInformationParser;
}
testWidgets('GoRouteInformationParser can parse route',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/'), context);
List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 1);
expect(matchesObj.uri.toString(), '/');
expect(matchesObj.extra, isNull);
expect(matches[0].matchedLocation, '/');
expect(matches[0].route, routes[0]);
final Object extra = Object();
matchesObj = await parser.parseRouteInformationWithDependencies(
createRouteInformation('/abc?def=ghi', extra), context);
matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), '/abc?def=ghi');
expect(matchesObj.extra, extra);
expect(matches[0].matchedLocation, '/');
expect(matches[0].route, routes[0]);
expect(matches[1].matchedLocation, '/abc');
expect(matches[1].route, routes[0].routes[0]);
});
testWidgets(
"GoRouteInformationParser can parse deeplink route and maintain uri's scheme and host",
(WidgetTester tester) async {
const String expectedScheme = 'https';
const String expectedHost = 'www.example.com';
const String expectedPath = '/abc';
const String expectedUriString =
'$expectedScheme://$expectedHost$expectedPath';
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation(expectedUriString), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), expectedUriString);
expect(matchesObj.uri.scheme, expectedScheme);
expect(matchesObj.uri.host, expectedHost);
expect(matchesObj.uri.path, expectedPath);
expect(matches[0].matchedLocation, '/');
expect(matches[0].route, routes[0]);
expect(matches[1].matchedLocation, '/abc');
expect(matches[1].route, routes[0].routes[0]);
});
testWidgets(
'GoRouteInformationParser can restore full route matches if optionURLReflectsImperativeAPIs is true',
(WidgetTester tester) async {
final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>();
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
builder: (_, __) => const Placeholder(),
),
],
),
];
GoRouter.optionURLReflectsImperativeAPIs = true;
final GoRouter router =
await createRouter(routes, tester, navigatorKey: navKey);
// Generate RouteMatchList with imperative route match
router.go('/abc');
await tester.pumpAndSettle();
router.push('/');
await tester.pumpAndSettle();
final RouteMatchList matchList = router.routerDelegate.currentConfiguration;
expect(matchList.uri.toString(), '/abc');
expect(matchList.matches.length, 3);
final RouteInformation restoredRouteInformation =
router.routeInformationParser.restoreRouteInformation(matchList)!;
expect(restoredRouteInformation.uri.path, '/');
// Can restore back to original RouteMatchList.
final RouteMatchList parsedRouteMatch = await router.routeInformationParser
.parseRouteInformationWithDependencies(
restoredRouteInformation, navKey.currentContext!);
expect(parsedRouteMatch.uri.toString(), '/abc');
expect(parsedRouteMatch.matches.length, 3);
GoRouter.optionURLReflectsImperativeAPIs = false;
});
test('GoRouteInformationParser can retrieve route by name', () async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
name: 'lowercase',
builder: (_, __) => const Placeholder(),
),
GoRoute(
path: 'efg',
name: 'camelCase',
builder: (_, __) => const Placeholder(),
),
GoRoute(
path: 'hij',
name: 'snake_case',
builder: (_, __) => const Placeholder(),
),
],
),
];
final RouteConfiguration configuration = createRouteConfiguration(
routes: routes,
redirectLimit: 100,
topRedirect: (_, __) => null,
navigatorKey: GlobalKey<NavigatorState>(),
);
expect(configuration.namedLocation('lowercase'), '/abc');
expect(configuration.namedLocation('camelCase'), '/efg');
expect(configuration.namedLocation('snake_case'), '/hij');
// With query parameters
expect(configuration.namedLocation('lowercase'), '/abc');
expect(
configuration.namedLocation('lowercase',
queryParameters: const <String, String>{'q': '1'}),
'/abc?q=1');
expect(
configuration.namedLocation('lowercase',
queryParameters: const <String, String>{'q': '1', 'g': '2'}),
'/abc?q=1&g=2');
});
test(
'GoRouteInformationParser can retrieve route by name with query parameters',
() async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
name: 'routeName',
builder: (_, __) => const Placeholder(),
),
],
),
];
final RouteConfiguration configuration = createRouteConfiguration(
routes: routes,
redirectLimit: 100,
topRedirect: (_, __) => null,
navigatorKey: GlobalKey<NavigatorState>(),
);
expect(
configuration
.namedLocation('routeName', queryParameters: const <String, dynamic>{
'q1': 'v1',
'q2': <String>['v2', 'v3'],
}),
'/abc?q1=v1&q2=v2&q2=v3',
);
});
testWidgets('GoRouteInformationParser returns error when unknown route',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/def'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 0);
expect(matchesObj.uri.toString(), '/def');
expect(matchesObj.extra, isNull);
expect(matchesObj.error!.toString(),
'GoException: no routes for location: /def');
});
testWidgets(
'GoRouteInformationParser calls redirector with correct uri when unknown route',
(WidgetTester tester) async {
String? lastRedirectLocation;
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: 'abc',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, GoRouterState state) {
lastRedirectLocation = state.uri.toString();
return null;
},
);
final BuildContext context = tester.element(find.byType(Router<Object>));
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/def'), context);
expect(lastRedirectLocation, '/def');
});
testWidgets('GoRouteInformationParser can work with route parameters',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: ':uid/family/:fid',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/123/family/456'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), '/123/family/456');
expect(matchesObj.pathParameters.length, 2);
expect(matchesObj.pathParameters['uid'], '123');
expect(matchesObj.pathParameters['fid'], '456');
expect(matchesObj.extra, isNull);
expect(matches[0].matchedLocation, '/');
expect(matches[1].matchedLocation, '/123/family/456');
});
testWidgets(
'GoRouteInformationParser processes top level redirect when there is no match',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: ':uid/family/:fid',
builder: (_, __) => const Placeholder(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (BuildContext context, GoRouterState state) {
if (state.uri.toString() != '/123/family/345') {
return '/123/family/345';
}
return null;
},
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/random/uri'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), '/123/family/345');
expect(matches[0].matchedLocation, '/');
expect(matches[1].matchedLocation, '/123/family/345');
});
testWidgets(
'GoRouteInformationParser can do route level redirect when there is a match',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/',
builder: (_, __) => const Placeholder(),
routes: <GoRoute>[
GoRoute(
path: ':uid/family/:fid',
builder: (_, __) => const Placeholder(),
),
GoRoute(
path: 'redirect',
redirect: (_, __) => '/123/family/345',
builder: (_, __) => throw UnimplementedError(),
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/redirect'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches.length, 2);
expect(matchesObj.uri.toString(), '/123/family/345');
expect(matches[0].matchedLocation, '/');
expect(matches[1].matchedLocation, '/123/family/345');
});
testWidgets(
'GoRouteInformationParser throws an exception when route is malformed',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/abc',
builder: (_, __) => const Placeholder(),
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirectLimit: 100,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
expect(() async {
await parser.parseRouteInformationWithDependencies(
createRouteInformation('::Not valid URI::'), context);
}, throwsA(isA<FormatException>()));
});
testWidgets(
'GoRouteInformationParser returns an error if a redirect is detected.',
(WidgetTester tester) async {
final List<GoRoute> routes = <GoRoute>[
GoRoute(
path: '/abc',
builder: (_, __) => const Placeholder(),
redirect: (BuildContext context, GoRouterState state) =>
state.uri.toString(),
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/abd'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches, hasLength(0));
expect(matchesObj.error, isNotNull);
});
testWidgets('Creates a match for ShellRoute', (WidgetTester tester) async {
final List<RouteBase> routes = <RouteBase>[
ShellRoute(
builder: (BuildContext context, GoRouterState state, Widget child) {
return Scaffold(
body: child,
);
},
routes: <RouteBase>[
GoRoute(
path: '/a',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen A'),
);
},
),
GoRoute(
path: '/b',
builder: (BuildContext context, GoRouterState state) {
return const Scaffold(
body: Text('Screen B'),
);
},
),
],
),
];
final GoRouteInformationParser parser = await createParser(
tester,
routes: routes,
redirect: (_, __) => null,
);
final BuildContext context = tester.element(find.byType(Router<Object>));
final RouteMatchList matchesObj =
await parser.parseRouteInformationWithDependencies(
createRouteInformation('/a'), context);
final List<RouteMatchBase> matches = matchesObj.matches;
expect(matches, hasLength(1));
final ShellRouteMatch match = matches.first as ShellRouteMatch;
expect(match.matches, hasLength(1));
expect(matchesObj.error, isNull);
});
}
| packages/packages/go_router/test/parser_test.dart/0 | {
"file_path": "packages/packages/go_router/test/parser_test.dart",
"repo_id": "packages",
"token_count": 6868
} | 1,056 |
## Usage
### Dependencies
To use `go_router_builder`, you need to have the following dependencies in
`pubspec.yaml`.
```yaml
dependencies:
# ...along with your other dependencies
go_router: ^9.0.3
dev_dependencies:
# ...along with your other dev-dependencies
build_runner: ^2.0.0
go_router_builder: ^2.3.0
```
### Source code
Instructions below explain how to create and annotate types to use this builder.
Along with importing the `go_router.dart` library, it's essential to also
include a `part` directive that references the generated Dart file. The
generated file will always have the name `[source_file].g.dart`.
```dart
import 'package:go_router/go_router.dart';
part 'this_file.g.dart';
```
### Running `build_runner`
To do a one-time build:
```console
flutter pub run build_runner build
```
Read more about using
[`build_runner` on pub.dev](https://pub.dev/packages/build_runner).
## Overview
`go_router` fundamentally relies on the ability to match a string-based location
in a URI format into one or more page builders, each that require zero or more
arguments that are passed as path and query parameters as part of the location.
`go_router` does a good job of making the path and query parameters available
via the `pathParameters` and `queryParameters` properties of the `GoRouterState` object, but
often the page builder must first parse the parameters into types that aren't
`String`s, e.g.
```dart
GoRoute(
path: ':authorId',
builder: (context, state) {
// require the authorId to be present and be an integer
final authorId = int.parse(state.pathParameters['authorId']!);
return AuthorDetailsScreen(authorId: authorId);
},
),
```
In this example, the `authorId` parameter is a) required and b) must be an
`int`. However, neither of these requirements are checked until run-time, making
it easy to write code that is not type-safe, e.g.
```dart
void _tap() => context.go('/author/a42'); // error: `a42` is not an `int`
```
Dart's type system allows mistakes to be caught at compile-time instead of
run-time. The goal of the routing is to provide a way to define the required and
optional parameters that a specific route consumes and to use code generation to
take out the drudgery of writing a bunch of `go`, `push` and `location`
boilerplate code implementations ourselves.
## Defining a route
Define each route as a class extending `GoRouteData` and overriding the `build`
method.
```dart
class HomeRoute extends GoRouteData {
const HomeRoute();
@override
Widget build(BuildContext context, GoRouterState state) => const HomeScreen();
}
```
## Route tree
The tree of routes is defined as an attribute on each of the top-level routes:
```dart
@TypedGoRoute<HomeRoute>(
path: '/',
routes: <TypedGoRoute<GoRouteData>>[
TypedGoRoute<FamilyRoute>(
path: 'family/:familyId',
)
],
)
class HomeRoute extends GoRouteData {
const HomeRoute();
@override
Widget build(BuildContext context, GoRouterState state) => HomeScreen(families: familyData);
}
@TypedGoRoute<LoginRoute>(path: '/login')
class LoginRoute extends GoRouteData {...}
```
## `GoRouter` initialization
The code generator aggregates all top-level routes into a single list called
`$appRoutes` for use in initializing the `GoRouter` instance:
```dart
final _router = GoRouter(routes: $appRoutes);
```
## Error builder
One can use typed routes to provide an error builder as well:
```dart
class ErrorRoute extends GoRouteData {
ErrorRoute({required this.error});
final Exception error;
@override
Widget build(BuildContext context, GoRouterState state) => ErrorScreen(error: error);
}
```
With this in place, you can provide the `errorBuilder` parameter like so:
```dart
final _router = GoRouter(
routes: $appRoutes,
errorBuilder: (c, s) => ErrorRoute(s.error!).build(c),
);
```
## Navigation
Navigate using the `go` or `push` methods provided by the code generator:
```dart
void _tap() => PersonRoute(fid: 'f2', pid: 'p1').go(context);
```
If you get this wrong, the compiler will complain:
```dart
// error: missing required parameter 'fid'
void _tap() => PersonRoute(pid: 'p1').go(context);
```
This is the point of typed routing: the error is found statically.
## Return value
Starting from `go_router` 6.5.0, pushing a route and subsequently popping it, can produce
a return value. The generated routes also follow this functionality.
```dart
void _tap() async {
final result = await PersonRoute(pid: 'p1').go(context);
}
```
## Query parameters
Parameters (named or positional) not listed in the path of `TypedGoRoute` indicate query parameters:
```dart
@TypedGoRoute(path: '/login')
class LoginRoute extends GoRouteData {
LoginRoute({this.from});
final String? from;
@override
Widget build(BuildContext context, GoRouterState state) => LoginScreen(from: from);
}
```
### Default values
For query parameters with a **non-nullable** type, you can define a default value:
```dart
@TypedGoRoute(path: '/my-route')
class MyRoute extends GoRouteData {
MyRoute({this.queryParameter = 'defaultValue'});
final String queryParameter;
@override
Widget build(BuildContext context, GoRouterState state) => MyScreen(queryParameter: queryParameter);
}
```
A query parameter that equals to its default value is not included in the location.
## Extra parameter
A route can consume an extra parameter by taking it as a typed constructor
parameter with the special name `$extra`:
```dart
class PersonRouteWithExtra extends GoRouteData {
PersonRouteWithExtra({this.$extra});
final int? $extra;
@override
Widget build(BuildContext context, GoRouterState state) => PersonScreen(personId: $extra);
}
```
Pass the extra param as a typed object:
```dart
void _tap() => PersonRouteWithExtra(Person(name: 'Marvin', age: 42)).go(context);
```
The `$extra` parameter is still passed outside the location, still defeats
dynamic and deep linking (including the browser back button) and is still not
recommended when targeting Flutter web.
## Mixed parameters
You can, of course, combine the use of path, query and $extra parameters:
```dart
@TypedGoRoute<HotdogRouteWithEverything>(path: '/:ketchup')
class HotdogRouteWithEverything extends GoRouteData {
HotdogRouteWithEverything(this.ketchup, this.mustard, this.$extra);
final bool ketchup; // required path parameter
final String? mustard; // optional query parameter
final Sauce $extra; // special $extra parameter
@override
Widget build(BuildContext context, GoRouterState state) => HotdogScreen(ketchup, mustard, $extra);
}
```
This seems kinda silly, but it works.
## Redirection
Redirect using the `location` property on a route provided by the code
generator:
```dart
redirect: (state) {
final loggedIn = loginInfo.loggedIn;
final loggingIn = state.matchedLocation == LoginRoute().location;
if( !loggedIn && !loggingIn ) return LoginRoute(from: state.matchedLocation).location;
if( loggedIn && loggingIn ) return HomeRoute().location;
return null;
}
```
## Route-level redirection
Handle route-level redirects by implementing the `redirect` method on the route:
```dart
class HomeRoute extends GoRouteData {
// no need to implement [build] when this [redirect] is unconditional
@override
String? redirect(BuildContext context, GoRouterState state) => BooksRoute().location;
}
```
## Type conversions
The code generator can convert simple types like `int` and `enum` to/from the
`String` type of the underlying pathParameters:
```dart
enum BookKind { all, popular, recent }
class BooksRoute extends GoRouteData {
BooksRoute({this.kind = BookKind.popular});
final BookKind kind;
@override
Widget build(BuildContext context, GoRouterState state) => BooksScreen(kind: kind);
}
```
## Transitions
By default, the `GoRouter` will use the app it finds in the widget tree, e.g.
`MaterialApp`, `CupertinoApp`, `WidgetApp`, etc. and use the corresponding page
type to create the page that wraps the `Widget` returned by the route's `build`
method, e.g. `MaterialPage`, `CupertinoPage`, `NoTransitionPage`, etc.
Furthermore, it will use the `state.pageKey` property to set the `key` property
of the page and the `restorationId` of the page.
### Transition override
If you'd like to change how the page is created, e.g. to use a different page
type, pass non-default parameters when creating the page (like a custom key) or
access the `GoRouteState` object, you can override the `buildPage`
method of the base class instead of the `build` method:
```dart
class MyMaterialRouteWithKey extends GoRouteData {
static final _key = LocalKey('my-route-with-key');
@override
MaterialPage<void> buildPage(BuildContext context, GoRouterState state) =>
MaterialPage<void>(
key: _key,
child: MyPage(),
);
}
```
### Custom transitions
Overriding the `buildPage` method is also useful for custom transitions:
```dart
class FancyRoute extends GoRouteData {
@override
MaterialPage<void> buildPage(BuildContext context, GoRouterState state) =>
CustomTransitionPage<void>(
key: state.pageKey,
child: FancyPage(),
transitionsBuilder: (context, animation, animation2, child) =>
RotationTransition(turns: animation, child: child),
),
}
```
## TypedShellRoute and navigator keys
There may be situations where a child route of a shell needs to be displayed on a
different navigator. This kind of scenarios can be achieved by declaring a
**static** navigator key named:
- `$navigatorKey` for ShellRoutes
- `$parentNavigatorKey` for GoRoutes
Example:
```dart
// For ShellRoutes:
final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>();
class MyShellRouteData extends ShellRouteData {
const MyShellRouteData();
static final GlobalKey<NavigatorState> $navigatorKey = shellNavigatorKey;
@override
Widget builder(BuildContext context, GoRouterState state, Widget navigator) {
// ...
}
}
// For GoRoutes:
class MyGoRouteData extends GoRouteData {
const MyGoRouteData();
static final GlobalKey<NavigatorState> $parentNavigatorKey = rootNavigatorKey;
@override
Widget build(BuildContext context, GoRouterState state) {
// ...
}
}
```
An example is available [here](https://github.com/flutter/packages/blob/main/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart).
## Run tests
To run unit tests, run command `dart tool/run_tests.dart` from `packages/go_router_builder/`.
To run tests in examples, run `flutter test` from `packages/go_router_builder/example`. | packages/packages/go_router_builder/README.md/0 | {
"file_path": "packages/packages/go_router_builder/README.md",
"repo_id": "packages",
"token_count": 3206
} | 1,057 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, unreachable_from_main
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
part 'shell_route_with_keys_example.g.dart';
void main() => runApp(App());
final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>();
class App extends StatelessWidget {
App({super.key});
@override
Widget build(BuildContext context) => MaterialApp.router(
routerConfig: _router,
);
final GoRouter _router = GoRouter(
routes: $appRoutes,
initialLocation: '/home',
navigatorKey: rootNavigatorKey,
);
}
@TypedShellRoute<MyShellRouteData>(
routes: <TypedRoute<RouteData>>[
TypedGoRoute<HomeRouteData>(path: '/home'),
TypedGoRoute<UsersRouteData>(
path: '/users',
routes: <TypedGoRoute<UserRouteData>>[
TypedGoRoute<UserRouteData>(path: ':id'),
],
),
],
)
class MyShellRouteData extends ShellRouteData {
const MyShellRouteData();
static final GlobalKey<NavigatorState> $navigatorKey = shellNavigatorKey;
@override
Widget builder(BuildContext context, GoRouterState state, Widget navigator) {
return MyShellRouteScreen(child: navigator);
}
}
class MyShellRouteScreen extends StatelessWidget {
const MyShellRouteScreen({required this.child, super.key});
final Widget child;
int getCurrentIndex(BuildContext context) {
final String location = GoRouterState.of(context).uri.toString();
if (location.startsWith('/users')) {
return 1;
}
return 0;
}
@override
Widget build(BuildContext context) {
final int selectedIndex = getCurrentIndex(context);
return Scaffold(
body: Row(
children: <Widget>[
NavigationRail(
destinations: const <NavigationRailDestination>[
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.group),
label: Text('Users'),
),
],
selectedIndex: selectedIndex,
onDestinationSelected: (int index) {
switch (index) {
case 0:
const HomeRouteData().go(context);
case 1:
const UsersRouteData().go(context);
}
},
),
const VerticalDivider(thickness: 1, width: 1),
Expanded(child: child),
],
),
);
}
}
class HomeRouteData extends GoRouteData {
const HomeRouteData();
@override
Widget build(BuildContext context, GoRouterState state) {
return const Center(child: Text('The home page'));
}
}
class UsersRouteData extends GoRouteData {
const UsersRouteData();
@override
Widget build(BuildContext context, GoRouterState state) {
return ListView(
children: <Widget>[
for (int userID = 1; userID <= 3; userID++)
ListTile(
title: Text('User $userID'),
onTap: () => UserRouteData(id: userID).go(context),
),
],
);
}
}
class DialogPage extends Page<void> {
/// A page to display a dialog.
const DialogPage({required this.child, super.key});
/// The widget to be displayed which is usually a [Dialog] widget.
final Widget child;
@override
Route<void> createRoute(BuildContext context) {
return DialogRoute<void>(
context: context,
settings: this,
builder: (BuildContext context) => child,
);
}
}
class UserRouteData extends GoRouteData {
const UserRouteData({required this.id});
// Without this static key, the dialog will not cover the navigation rail.
static final GlobalKey<NavigatorState> $parentNavigatorKey = rootNavigatorKey;
final int id;
@override
Page<void> buildPage(BuildContext context, GoRouterState state) {
return DialogPage(
key: state.pageKey,
child: Center(
child: SizedBox(
width: 300,
height: 300,
child: Card(child: Center(child: Text('User $id'))),
),
),
);
}
}
| packages/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/lib/shell_route_with_keys_example.dart",
"repo_id": "packages",
"token_count": 1739
} | 1,058 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:go_router_builder_example/stateful_shell_route_initial_location_example.dart';
void main() {
testWidgets(
'Navigate to Notifications section with old tab selected by default',
(WidgetTester tester) async {
await tester.pumpWidget(App());
expect(find.text('Home'), findsOneWidget);
await tester.tap(find.text('Notifications'));
await tester.pumpAndSettle();
expect(find.text('Old notifications'), findsOneWidget);
},
);
}
| packages/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart/0 | {
"file_path": "packages/packages/go_router_builder/example/test/stateful_shell_route_initial_location_test.dart",
"repo_id": "packages",
"token_count": 233
} | 1,059 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
/// A codec that can encode/decode JWT payloads.
///
/// See https://www.rfc-editor.org/rfc/rfc7519#section-3
final Codec<Object?, String> _jwtCodec = json.fuse(utf8).fuse(base64);
/// A RegExp that can match, and extract parts from a JWT Token.
///
/// A JWT token consists of 3 base-64 encoded parts of data separated by periods:
///
/// header.payload.signature
///
/// More info: https://regexr.com/789qc
final RegExp _jwtTokenRegexp = RegExp(
r'^(?<header>[^\.\s]+)\.(?<payload>[^\.\s]+)\.(?<signature>[^\.\s]+)$');
/// Decodes the `claims` of a JWT token and returns them as a Map.
///
/// JWT `claims` are stored as a JSON object in the `payload` part of the token.
///
/// (This method does not validate the signature of the token.)
///
/// See https://www.rfc-editor.org/rfc/rfc7519#section-3
Map<String, Object?>? decodePayload(String? token) {
if (token != null) {
final RegExpMatch? match = _jwtTokenRegexp.firstMatch(token);
if (match != null) {
return _decodeJwtPayload(match.namedGroup('payload'));
}
}
return null;
}
/// Decodes a JWT payload using the [_jwtCodec].
Map<String, Object?>? _decodeJwtPayload(String? payload) {
try {
// Payload must be normalized before passing it to the codec
return _jwtCodec.decode(base64.normalize(payload!))
as Map<String, Object?>?;
} catch (_) {
// Do nothing, we always return null for any failure.
}
return null;
}
| packages/packages/google_identity_services_web/example/lib/src/jwt.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/example/lib/src/jwt.dart",
"repo_id": "packages",
"token_count": 581
} | 1,060 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Authentication. API reference:
// https://developers.google.com/identity/gsi/web/reference/js-reference
// ignore_for_file: non_constant_identifier_names
// * non_constant_identifier_names required to be able to use the same parameter
// names as the underlying JS library.
import 'dart:js_interop';
import 'shared.dart';
/// Binding to the `google.accounts.id` JS global.
///
/// See: https://developers.google.com/identity/gsi/web/reference/js-reference
@JS('google.accounts.id')
external GoogleAccountsId get id;
/// The Dart definition of the `google.accounts.id` global.
@JS()
@staticInterop
abstract class GoogleAccountsId {}
/// The `google.accounts.id` methods
extension GoogleAccountsIdExtension on GoogleAccountsId {
/// An undocumented method.
///
/// Try it with 'debug'.
void setLogLevel(String level) => _setLogLevel(level.toJS);
@JS('setLogLevel')
external void _setLogLevel(JSString level);
/// Initializes the Sign In With Google client based on [IdConfiguration].
///
/// The `initialize` method creates a Sign In With Google client instance that
/// can be implicitly used by all modules in the same web page.
///
/// * You only need to call the `initialize` method once even if you use
/// multiple modules (like One Tap, Personalized button, revocation, etc.) in
/// the same web page.
/// * If you do call the google.accounts.id.initialize method multiple times,
/// only the configurations in the last call will be remembered and used.
///
/// You actually reset the configurations whenever you call the `initialize`
/// method, and all subsequent methods in the same web page will use the new
/// configurations immediately.
///
/// WARNING: The `initialize` method should be called only once, even if you
/// use both One Tap and button in the same web page.
///
/// Method: google.accounts.id.initialize
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.initialize
external void initialize(IdConfiguration idConfiguration);
/// The `prompt` method displays the One Tap prompt or the browser native
/// credential manager after the [initialize] method is invoked.
///
/// Normally, the `prompt` method is called on page load. Due to the session
/// status and user settings on the Google side, the One Tap prompt UI might
/// not be displayed. To get notified on the UI status for different moments,
/// pass a [PromptMomentListenerFn] to receive UI status notifications.
///
/// Notifications are fired on the following moments:
///
/// * Display moment: This occurs after the `prompt` method is called. The
/// notification contains a boolean value to indicate whether the UI is
/// displayed or not.
/// * Skipped moment: This occurs when the One Tap prompt is closed by an auto
/// cancel, a manual cancel, or when Google fails to issue a credential, such
/// as when the selected session has signed out of Google.
/// In these cases, we recommend that you continue on to the next identity
/// providers, if there are any.
/// * Dismissed moment: This occurs when Google successfully retrieves a
/// credential or a user wants to stop the credential retrieval flow. For
/// example, when the user begins to input their username and password in
/// your login dialog, you can call the [cancel] method to close the One Tap
/// prompt and trigger a dismissed moment.
///
/// WARNING: When on a dismissed moment, do not try any of the next identity
/// providers.
///
/// Method: google.accounts.id.prompt
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.prompt
void prompt([PromptMomentListenerFn? momentListener]) {
if (momentListener == null) {
return _prompt();
}
return _promptWithListener(momentListener.toJS);
}
@JS('prompt')
external void _prompt();
@JS('prompt')
external void _promptWithListener(JSFunction momentListener);
/// Renders a Sign In With Google button in your web page.
///
/// Method: google.accounts.id.renderButton
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.renderButton
void renderButton(
Object parent, [
GsiButtonConfiguration? options,
]) {
assert(parent is JSObject,
'parent must be a JSObject. Use package:web to retrieve/create one.');
parent as JSObject;
if (options == null) {
return _renderButton(parent);
}
return _renderButtonWithOptions(parent, options);
}
@JS('renderButton')
external void _renderButton(JSObject parent);
@JS('renderButton')
external void _renderButtonWithOptions(
JSObject parent, GsiButtonConfiguration options);
/// Record when the user signs out of your website in cookies.
///
/// This prevents a UX dead loop.
///
/// Method: google.accounts.id.disableAutoselect
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.disableAutoSelect
external void disableAutoSelect();
/// A wrapper for the `store` method of the browser's native credential manager API.
///
/// It can only be used to store a Password [Credential].
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/store
///
/// Method: google.accounts.id.storeCredential
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.storeCredential
void storeCredential(Credential credential, [VoidFn? callback]) {
if (callback == null) {
return _jsStoreCredential(credential);
}
return _jsStoreCredentialWithCallback(credential, callback.toJS);
}
@JS('storeCredential')
external void _jsStoreCredential(Credential credential);
@JS('storeCredential')
external void _jsStoreCredentialWithCallback(
Credential credential, JSFunction callback);
/// Cancels the One Tap flow.
///
/// You can cancel the One Tap flow if you remove the prompt from the relying
/// party DOM. The cancel operation is ignored if a credential is already
/// selected.
///
/// Method: google.accounts.id.cancel
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.cancel
external void cancel();
/// Revokes the OAuth grant used to share the ID token for the specified user.
///
/// [hint] is the email address or unique ID of the user's Google Account. The
/// ID is the `sub` property of the [CredentialResponse.credential] payload.
///
/// The optional [callback] is a function that gets called to report on the
/// success of the revocation call.
///
/// Method: google.accounts.id.revoke
/// https://developers.google.com/identity/gsi/web/reference/js-reference#google.accounts.id.revoke
void revoke(String hint, [RevocationResponseHandlerFn? callback]) {
if (callback == null) {
return _revoke(hint.toJS);
}
return _revokeWithCallback(hint.toJS, callback.toJS);
}
@JS('revoke')
external void _revoke(JSString hint);
@JS('revoke')
external void _revokeWithCallback(JSString hint, JSFunction callback);
}
/// The configuration object for the [initialize] method.
///
/// Data type: IdConfiguration
/// https://developers.google.com/identity/gsi/web/reference/js-reference#IdConfiguration
@JS()
@anonymous
@staticInterop
abstract class IdConfiguration {
/// Constructs a IdConfiguration object in JavaScript.
factory IdConfiguration({
/// Your application's client ID, which is found and created in the Google
/// Developers Console.
required String client_id,
/// Determines if an ID token is automatically returned without any user
/// interaction when there's only one Google session that has approved your
/// app before. The default value is `false`.
bool? auto_select,
/// The function that handles the ID token returned from the One Tap prompt
/// or the pop-up window. This attribute is required if Google One Tap or
/// the Sign In With Google button `popup` UX mode is used.
CallbackFn? callback,
/// This attribute is the URI of your login endpoint. May be omitted if the
/// current page is your login page, in which case the credential is posted
/// to this page by default.
///
/// The ID token credential response is posted to your login endpoint when
/// a user clicks on the Sign In With Google button and `redirect` UX mode
/// is used.
///
/// Your login endpoint must handle POST requests containing a credential
/// key with an ID token value in the body.
Uri? login_uri,
/// The function that handles the password credential returned from the
/// browser's native credential manager.
NativeCallbackFn? native_callback,
/// Whether or not to cancel the One Tap request if a user clicks outside
/// the prompt. The default value is `true`.
bool? cancel_on_tap_outside,
/// The DOM ID of the container element. If it's not set, the One Tap prompt
/// is displayed in the top-right corner of the window.
String? prompt_parent_id,
/// A random string used by the ID token to prevent replay attacks.
///
/// Nonce length is limited to the maximum JWT size supported by your
/// environment, and individual browser and server HTTP size constraints.
String? nonce,
/// Changes the text of the title and messages in the One Tap prompt.
OneTapContext? context,
/// If you need to display One Tap in the parent domain and its subdomains,
/// pass the parent domain to this field so that a single shared-state
/// cookie is used.
///
/// See: https://developers.google.com/identity/gsi/web/guides/subdomains
String? state_cookie_domain,
/// Set the UX flow used by the Sign In With Google button. The default
/// value is `popup`. **This attribute has no impact on the OneTap UX.**
UxMode? ux_mode,
/// The origins that are allowed to embed the intermediate iframe. One Tap
/// will run in the intermediate iframe mode if this field presents.
///
/// Wildcard prefixes are also supported. Wildcard domains must begin with
/// a secure `https://` scheme, otherwise they'll be considered invalid.
List<String>? allowed_parent_origin,
/// Overrides the default intermediate iframe behavior when users manually
/// close One Tap by tapping on the 'X' button in the One Tap UI. The
/// default behavior is to remove the intermediate iframe from the DOM
/// immediately.
///
/// The `intermediate_iframe_close_callback` field takes effect only in
/// intermediate iframe mode. And it has impact only to the intermediate
/// iframe, instead of the One Tap iframe. The One Tap UI is removed before
/// the callback is invoked.
VoidFn? intermediate_iframe_close_callback,
/// Determines if the upgraded One Tap UX should be enabled on browsers
/// that support Intelligent Tracking Prevention (ITP). The default value
/// is false.
///
/// See: https://developers.google.com/identity/gsi/web/guides/features#upgraded_ux_on_itp_browsers
bool? itp_support,
/// If your application knows in advance which user should be signed-in, it
/// can provide a login hint to Google.
///
/// When successful, account selection is skipped. Accepted values are:
/// * an email address or
/// * an ID token sub field value.
///
/// For more information, see:
/// * https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters
String? login_hint,
/// When a user has multiple accounts and should only sign-in with their
/// Workspace account use this to provide a domain name hint to Google.
///
/// When successful, user accounts displayed during account selection are
/// limited to the provided domain.
///
/// A wildcard value: `*` offers only Workspace accounts to the user and
/// excludes consumer accounts ([email protected]) during account selection.
///
/// For more information, see:
/// * https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters
String? hd,
/// Allow the browser to control user sign-in prompts and mediate the
/// sign-in flow between your website and Google. Defaults to false.
bool? use_fedcm_for_prompt,
}) {
return IdConfiguration._toJS(
client_id: client_id.toJS,
auto_select: auto_select?.toJS,
callback: callback?.toJS,
login_uri: login_uri?.toString().toJS,
native_callback: native_callback?.toJS,
cancel_on_tap_outside: cancel_on_tap_outside?.toJS,
prompt_parent_id: prompt_parent_id?.toJS,
nonce: nonce?.toJS,
context: context?.toString().toJS,
state_cookie_domain: state_cookie_domain?.toJS,
ux_mode: ux_mode?.toString().toJS,
allowed_parent_origin:
allowed_parent_origin?.map((String s) => s.toJS).toList().toJS,
intermediate_iframe_close_callback:
intermediate_iframe_close_callback?.toJS,
itp_support: itp_support?.toJS,
login_hint: login_hint?.toJS,
hd: hd?.toJS,
use_fedcm_for_prompt: use_fedcm_for_prompt?.toJS,
);
}
// `IdConfiguration`'s external factory, defined as JSTypes. This is the actual JS-interop bit.
external factory IdConfiguration._toJS({
JSString? client_id,
JSBoolean? auto_select,
JSFunction? callback,
JSString? login_uri,
JSFunction? native_callback,
JSBoolean? cancel_on_tap_outside,
JSString? prompt_parent_id,
JSString? nonce,
JSString? context,
JSString? state_cookie_domain,
JSString? ux_mode,
JSArray<JSString>? allowed_parent_origin,
JSFunction? intermediate_iframe_close_callback,
JSBoolean? itp_support,
JSString? login_hint,
JSString? hd,
JSBoolean? use_fedcm_for_prompt,
});
}
/// The type of the function that can be passed to [prompt] to listen for [PromptMomentNotification]s.
typedef PromptMomentListenerFn = void Function(PromptMomentNotification moment);
/// A moment (status) notification from the [prompt] method.
///
/// Data type: PromptMomentNotification
/// https://developers.google.com/identity/gsi/web/reference/js-reference#PromptMomentNotification
@JS()
@staticInterop
abstract class PromptMomentNotification {}
/// The methods of the [PromptMomentNotification] data type:
extension PromptMomentNotificationExtension on PromptMomentNotification {
/// Is this notification for a display moment?
bool isDisplayMoment() => _isDisplayMoment().toDart;
@JS('isDisplayMoment')
external JSBoolean _isDisplayMoment();
/// Is this notification for a display moment, and the UI is displayed?
bool isDisplayed() => _isDisplayed().toDart;
@JS('isDisplayed')
external JSBoolean _isDisplayed();
/// Is this notification for a display moment, and the UI isn't displayed?
bool isNotDisplayed() => _isNotDisplayed().toDart;
@JS('isNotDisplayed')
external JSBoolean _isNotDisplayed();
/// Is this notification for a skipped moment?
bool isSkippedMoment() => _isSkippedMoment().toDart;
@JS('isSkippedMoment')
external JSBoolean _isSkippedMoment();
/// Is this notification for a dismissed moment?
bool isDismissedMoment() => _isDismissedMoment().toDart;
@JS('isDismissedMoment')
external JSBoolean _isDismissedMoment();
/// The moment type.
MomentType getMomentType() =>
MomentType.values.byName(_getMomentType().toDart);
@JS('getMomentType')
external JSString _getMomentType();
/// The detailed reason why the UI isn't displayed.
MomentNotDisplayedReason? getNotDisplayedReason() => maybeEnum(
_getNotDisplayedReason()?.toDart, MomentNotDisplayedReason.values);
@JS('getNotDisplayedReason')
external JSString? _getNotDisplayedReason();
/// The detailed reason for the skipped moment.
MomentSkippedReason? getSkippedReason() =>
maybeEnum(_getSkippedReason()?.toDart, MomentSkippedReason.values);
@JS('getSkippedReason')
external JSString? _getSkippedReason();
/// The detailed reason for the dismissal.
MomentDismissedReason? getDismissedReason() =>
maybeEnum(_getDismissedReason()?.toDart, MomentDismissedReason.values);
@JS('getDismissedReason')
external JSString? _getDismissedReason();
}
/// The object passed as the parameter of your [CallbackFn].
///
/// Data type: CredentialResponse
/// https://developers.google.com/identity/gsi/web/reference/js-reference#CredentialResponse
@JS()
@staticInterop
abstract class CredentialResponse {}
/// The fields that are contained in the credential response object.
extension CredentialResponseExtension on CredentialResponse {
/// The ClientID for this Credential.
String? get client_id => _client_id?.toDart;
@JS('client_id')
external JSString? get _client_id;
/// Error while signing in.
String? get error => _error?.toDart;
@JS('error')
external JSString? get _error;
/// Details of the error while signing in.
String? get error_detail => _error_detail?.toDart;
@JS('error_detail')
external JSString? get _error_detail;
/// This field is the ID token as a base64-encoded JSON Web Token (JWT)
/// string.
///
/// See more: https://developers.google.com/identity/gsi/web/reference/js-reference#credential
String? get credential => _credential?.toDart;
@JS('credential')
external JSString? get _credential;
/// This field sets how the credential was selected.
///
/// The type of button used along with the session and consent state are used
/// to set the value.
///
/// See more: https://developers.google.com/identity/gsi/web/reference/js-reference#select_by
CredentialSelectBy? get select_by =>
maybeEnum(_select_by?.toDart, CredentialSelectBy.values);
@JS('select_by')
external JSString? get _select_by;
}
/// The type of the `callback` used to create an [IdConfiguration].
///
/// Describes a JavaScript function that handles ID tokens from
/// [CredentialResponse]s.
///
/// Google One Tap and the Sign In With Google button popup UX mode use this
/// attribute.
typedef CallbackFn = void Function(CredentialResponse credentialResponse);
/// The configuration object for the [renderButton] method.
///
/// Data type: GsiButtonConfiguration
/// https://developers.google.com/identity/gsi/web/reference/js-reference#GsiButtonConfiguration
@JS()
@anonymous
@staticInterop
abstract class GsiButtonConfiguration {
/// Constructs an options object for the [renderButton] method.
factory GsiButtonConfiguration({
/// The button type.
ButtonType? type,
/// The button theme.
ButtonTheme? theme,
/// The button size.
ButtonSize? size,
/// The button text.
ButtonText? text,
/// The button shape.
ButtonShape? shape,
/// The Google logo alignment in the button.
ButtonLogoAlignment? logo_alignment,
/// The minimum button width, in pixels.
///
/// The maximum width is 400 pixels.
double? width,
/// The pre-set locale of the button text.
///
/// If not set, the browser's default locale or the Google session user's
/// preference is used.
String? locale,
/// A function to be called when the button is clicked.
GsiButtonClickListenerFn? click_listener,
}) {
return GsiButtonConfiguration._toJS(
type: type.toString().toJS,
theme: theme.toString().toJS,
size: size.toString().toJS,
text: text?.toString().toJS,
shape: shape?.toString().toJS,
logo_alignment: logo_alignment?.toString().toJS,
width: width?.toJS,
locale: locale?.toJS,
click_listener: click_listener?.toJS,
);
}
// `GsiButtonConfiguration`'s external factory, defined as JSTypes.
external factory GsiButtonConfiguration._toJS({
JSString? type,
JSString? theme,
JSString? size,
JSString? text,
JSString? shape,
JSString? logo_alignment,
JSNumber? width,
JSString? locale,
JSFunction? click_listener,
});
}
/// The object passed as an optional parameter to `click_listener` function.
@JS()
@staticInterop
abstract class GsiButtonData {}
/// The fields that are contained in the button data.
extension GsiButtonDataExtension on GsiButtonData {
/// Nonce
String? get nonce => _nonce?.toDart;
@JS('nonce')
external JSString? get _nonce;
/// State
String? get state => _state?.toDart;
@JS('state')
external JSString? get _state;
}
/// The type of the [GsiButtonConfiguration] `click_listener` function.
typedef GsiButtonClickListenerFn = void Function(GsiButtonData? gsiButtonData);
/// The object passed to the [NativeCallbackFn]. Represents a PasswordCredential
/// that was returned by the Browser.
///
/// `Credential` objects can also be programmatically created to be stored
/// in the browser through the [storeCredential] method.
///
/// See also: https://developer.mozilla.org/en-US/docs/Web/API/PasswordCredential/PasswordCredential
///
/// Data type: Credential
/// https://developers.google.com/identity/gsi/web/reference/js-reference#type-Credential
@JS()
@anonymous
@staticInterop
abstract class Credential {
///
factory Credential({
required String id,
required String password,
}) =>
Credential._toJS(
id: id.toJS,
password: password.toJS,
);
external factory Credential._toJS({
JSString id,
JSString password,
});
}
/// The fields that are contained in the [Credential] object.
extension CredentialExtension on Credential {
/// Identifies the user.
String? get id => _id.toDart;
@JS('id')
external JSString get _id;
/// The password.
String? get password => _password.toDart;
@JS('password')
external JSString get _password;
}
/// The type of the `native_callback` used to create an [IdConfiguration].
///
/// Describes a JavaScript function that handles password [Credential]s coming
/// from the native Credential manager of the user's browser.
typedef NativeCallbackFn = void Function(Credential credential);
/*
// Library load callback: onGoogleLibraryLoad
// https://developers.google.com/identity/gsi/web/reference/js-reference#onGoogleLibraryLoad
// See: `load_callback.dart` and `loader.dart`
*/
/// The type of the `callback` function passed to [revoke], to be notified of
/// the success of the revocation operation.
typedef RevocationResponseHandlerFn = void Function(
RevocationResponse revocationResponse,
);
/// The parameter passed to the `callback` of the [revoke] function.
///
/// Data type: RevocationResponse
/// https://developers.google.com/identity/gsi/web/reference/js-reference#RevocationResponse
@JS()
@staticInterop
abstract class RevocationResponse {}
/// The fields that are contained in the [RevocationResponse] object.
extension RevocationResponseExtension on RevocationResponse {
/// This field is a boolean value set to true if the revoke method call
/// succeeded or false on failure.
bool get successful => _successful.toDart;
@JS('successful')
external JSBoolean get _successful;
/// This field is a string value and contains a detailed error message if the
/// revoke method call failed, it is undefined on success.
String? get error => _error?.toDart;
@JS('error')
external JSString? get _error;
}
| packages/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart/0 | {
"file_path": "packages/packages/google_identity_services_web/lib/src/js_interop/google_accounts_id.dart",
"repo_id": "packages",
"token_count": 7326
} | 1,061 |
# Google Maps for Flutter
<?code-excerpt path-base="example/lib"?>
[](https://pub.dev/packages/google_maps_flutter)
A Flutter plugin that provides a [Google Maps](https://developers.google.com/maps/) widget.
| | Android | iOS | Web |
|-------------|---------|---------|----------------------------------|
| **Support** | SDK 20+ | iOS 12+ | Same as [Flutter's][web-support] |
[web-support]: https://docs.flutter.dev/reference/supported-platforms
## Usage
To use this plugin, add `google_maps_flutter` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels).
## Getting Started
* Get an API key at <https://cloud.google.com/maps-platform/>.
* Enable Google Map SDK for each platform.
* Go to [Google Developers Console](https://console.cloud.google.com/).
* Choose the project that you want to enable Google Maps on.
* Select the navigation menu and then select "Google Maps".
* Select "APIs" under the Google Maps menu.
* To enable Google Maps for Android, select "Maps SDK for Android" in the "Additional APIs" section, then select "ENABLE".
* To enable Google Maps for iOS, select "Maps SDK for iOS" in the "Additional APIs" section, then select "ENABLE".
* To enable Google Maps for Web, enable the "Maps JavaScript API".
* Make sure the APIs you enabled are under the "Enabled APIs" section.
For more details, see [Getting started with Google Maps Platform](https://developers.google.com/maps/gmp-get-started).
### Android
1. Set the `minSdkVersion` in `android/app/build.gradle`:
```groovy
android {
defaultConfig {
minSdkVersion 20
}
}
```
This means that app will only be available for users that run Android SDK 20 or higher.
2. Specify your API key in the application manifest `android/app/src/main/AndroidManifest.xml`:
```xml
<manifest ...
<application ...
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR KEY HERE"/>
```
#### Display Mode
The Android implementation supports multiple
[platform view display modes](https://flutter.dev/docs/development/platform-integration/platform-views).
For details, see [the Android README](https://pub.dev/packages/google_maps_flutter_android#display-mode).
#### Cloud-based map styling
Cloud-based map styling works on Android only if `AndroidMapRenderer.latest` map renderer has been initialized.
For details, see [the Android README](https://pub.dev/packages/google_maps_flutter_android#map-renderer).
### iOS
To set up, specify your API key in the application delegate `ios/Runner/AppDelegate.m`:
```objectivec
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:@"YOUR KEY HERE"];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
```
Or in your swift code, specify your API key in the application delegate `ios/Runner/AppDelegate.swift`:
```swift
import UIKit
import Flutter
import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("YOUR KEY HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
```
### Web
You'll need to modify the `web/index.html` file of your Flutter Web application
to include the Google Maps JS SDK.
Check [the `google_maps_flutter_web` README](https://pub.dev/packages/google_maps_flutter_web)
for the latest information on how to prepare your App to use Google Maps on the
web.
### All
You can now add a `GoogleMap` widget to your widget tree.
The map view can be controlled with the `GoogleMapController` that is passed to
the `GoogleMap`'s `onMapCreated` callback.
The `GoogleMap` widget should be used within a widget with a bounded size. Using it
in an unbounded widget will cause the application to throw a Flutter exception.
### Sample Usage
<?code-excerpt "readme_sample.dart (MapSample)"?>
```dart
class MapSample extends StatefulWidget {
const MapSample({super.key});
@override
State<MapSample> createState() => MapSampleState();
}
class MapSampleState extends State<MapSample> {
final Completer<GoogleMapController> _controller =
Completer<GoogleMapController>();
static const CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
static const CameraPosition _kLake = CameraPosition(
bearing: 192.8334901395799,
target: LatLng(37.43296265331129, -122.08832357078792),
tilt: 59.440717697143555,
zoom: 19.151926040649414);
@override
Widget build(BuildContext context) {
return Scaffold(
body: GoogleMap(
mapType: MapType.hybrid,
initialCameraPosition: _kGooglePlex,
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _goToTheLake,
label: const Text('To the lake!'),
icon: const Icon(Icons.directions_boat),
),
);
}
Future<void> _goToTheLake() async {
final GoogleMapController controller = await _controller.future;
await controller.animateCamera(CameraUpdate.newCameraPosition(_kLake));
}
}
```
See the `example` directory for a complete sample app.
| packages/packages/google_maps_flutter/google_maps_flutter/README.md/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/README.md",
"repo_id": "packages",
"token_count": 1914
} | 1,062 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'page.dart';
class PlacePolygonPage extends GoogleMapExampleAppPage {
const PlacePolygonPage({Key? key})
: super(const Icon(Icons.linear_scale), 'Place polygon', key: key);
@override
Widget build(BuildContext context) {
return const PlacePolygonBody();
}
}
class PlacePolygonBody extends StatefulWidget {
const PlacePolygonBody({super.key});
@override
State<StatefulWidget> createState() => PlacePolygonBodyState();
}
class PlacePolygonBodyState extends State<PlacePolygonBody> {
PlacePolygonBodyState();
GoogleMapController? controller;
Map<PolygonId, Polygon> polygons = <PolygonId, Polygon>{};
Map<PolygonId, double> polygonOffsets = <PolygonId, double>{};
int _polygonIdCounter = 0;
PolygonId? selectedPolygon;
// Values when toggling polygon color
int strokeColorsIndex = 0;
int fillColorsIndex = 0;
List<Color> colors = <Color>[
Colors.purple,
Colors.red,
Colors.green,
Colors.pink,
];
// Values when toggling polygon width
int widthsIndex = 0;
List<int> widths = <int>[10, 20, 5];
// ignore: use_setters_to_change_properties
void _onMapCreated(GoogleMapController controller) {
this.controller = controller;
}
@override
void dispose() {
super.dispose();
}
void _onPolygonTapped(PolygonId polygonId) {
setState(() {
selectedPolygon = polygonId;
});
}
void _remove(PolygonId polygonId) {
setState(() {
if (polygons.containsKey(polygonId)) {
polygons.remove(polygonId);
}
selectedPolygon = null;
});
}
void _add() {
final int polygonCount = polygons.length;
if (polygonCount == 12) {
return;
}
final String polygonIdVal = 'polygon_id_$_polygonIdCounter';
final PolygonId polygonId = PolygonId(polygonIdVal);
final Polygon polygon = Polygon(
polygonId: polygonId,
consumeTapEvents: true,
strokeColor: Colors.orange,
strokeWidth: 5,
fillColor: Colors.green,
points: _createPoints(),
onTap: () {
_onPolygonTapped(polygonId);
},
);
setState(() {
polygons[polygonId] = polygon;
polygonOffsets[polygonId] = _polygonIdCounter.ceilToDouble();
// increment _polygonIdCounter to have unique polygon id each time
_polygonIdCounter++;
});
}
void _toggleGeodesic(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
geodesicParam: !polygon.geodesic,
);
});
}
void _toggleVisible(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
visibleParam: !polygon.visible,
);
});
}
void _changeStrokeColor(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
strokeColorParam: colors[++strokeColorsIndex % colors.length],
);
});
}
void _changeFillColor(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
fillColorParam: colors[++fillColorsIndex % colors.length],
);
});
}
void _changeWidth(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
strokeWidthParam: widths[++widthsIndex % widths.length],
);
});
}
void _addHoles(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] =
polygon.copyWith(holesParam: _createHoles(polygonId));
});
}
void _removeHoles(PolygonId polygonId) {
final Polygon polygon = polygons[polygonId]!;
setState(() {
polygons[polygonId] = polygon.copyWith(
holesParam: <List<LatLng>>[],
);
});
}
@override
Widget build(BuildContext context) {
final PolygonId? selectedId = selectedPolygon;
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: SizedBox(
width: 350.0,
height: 300.0,
child: GoogleMap(
initialCameraPosition: const CameraPosition(
target: LatLng(52.4478, -3.5402),
zoom: 7.0,
),
polygons: Set<Polygon>.of(polygons.values),
onMapCreated: _onMapCreated,
),
),
),
Expanded(
child: SingleChildScrollView(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: <Widget>[
Column(
children: <Widget>[
TextButton(
onPressed: _add,
child: const Text('add'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _remove(selectedId),
child: const Text('remove'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _toggleVisible(selectedId),
child: const Text('toggle visible'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _toggleGeodesic(selectedId),
child: const Text('toggle geodesic'),
),
],
),
Column(
children: <Widget>[
TextButton(
onPressed: (selectedId == null)
? null
: ((polygons[selectedId]!.holes.isNotEmpty)
? null
: () => _addHoles(selectedId)),
child: const Text('add holes'),
),
TextButton(
onPressed: (selectedId == null)
? null
: ((polygons[selectedId]!.holes.isEmpty)
? null
: () => _removeHoles(selectedId)),
child: const Text('remove holes'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _changeWidth(selectedId),
child: const Text('change stroke width'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _changeStrokeColor(selectedId),
child: const Text('change stroke color'),
),
TextButton(
onPressed: (selectedId == null)
? null
: () => _changeFillColor(selectedId),
child: const Text('change fill color'),
),
],
)
],
)
],
),
),
),
],
);
}
List<LatLng> _createPoints() {
final List<LatLng> points = <LatLng>[];
final double offset = _polygonIdCounter.ceilToDouble();
points.add(_createLatLng(51.2395 + offset, -3.4314));
points.add(_createLatLng(53.5234 + offset, -3.5314));
points.add(_createLatLng(52.4351 + offset, -4.5235));
points.add(_createLatLng(52.1231 + offset, -5.0829));
return points;
}
List<List<LatLng>> _createHoles(PolygonId polygonId) {
final List<List<LatLng>> holes = <List<LatLng>>[];
final double offset = polygonOffsets[polygonId]!;
final List<LatLng> hole1 = <LatLng>[];
hole1.add(_createLatLng(51.8395 + offset, -3.8814));
hole1.add(_createLatLng(52.0234 + offset, -3.9914));
hole1.add(_createLatLng(52.1351 + offset, -4.4435));
hole1.add(_createLatLng(52.0231 + offset, -4.5829));
holes.add(hole1);
final List<LatLng> hole2 = <LatLng>[];
hole2.add(_createLatLng(52.2395 + offset, -3.6814));
hole2.add(_createLatLng(52.4234 + offset, -3.7914));
hole2.add(_createLatLng(52.5351 + offset, -4.2435));
hole2.add(_createLatLng(52.4231 + offset, -4.3829));
holes.add(hole2);
return holes;
}
LatLng _createLatLng(double lat, double lng) {
return LatLng(lat, lng);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/example/lib/place_polygon.dart",
"repo_id": "packages",
"token_count": 4855
} | 1,063 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: library_private_types_in_public_api
part of '../google_maps_flutter.dart';
/// Controller for a single GoogleMap instance running on the host platform.
class GoogleMapController {
GoogleMapController._(
this._googleMapState, {
required this.mapId,
}) {
_connectStreams(mapId);
}
/// The mapId for this controller
final int mapId;
/// Initialize control of a [GoogleMap] with [id].
///
/// Mainly for internal use when instantiating a [GoogleMapController] passed
/// in [GoogleMap.onMapCreated] callback.
static Future<GoogleMapController> init(
int id,
CameraPosition initialCameraPosition,
_GoogleMapState googleMapState,
) async {
await GoogleMapsFlutterPlatform.instance.init(id);
return GoogleMapController._(
googleMapState,
mapId: id,
);
}
final _GoogleMapState _googleMapState;
void _connectStreams(int mapId) {
if (_googleMapState.widget.onCameraMoveStarted != null) {
GoogleMapsFlutterPlatform.instance
.onCameraMoveStarted(mapId: mapId)
.listen((_) => _googleMapState.widget.onCameraMoveStarted!());
}
if (_googleMapState.widget.onCameraMove != null) {
GoogleMapsFlutterPlatform.instance.onCameraMove(mapId: mapId).listen(
(CameraMoveEvent e) => _googleMapState.widget.onCameraMove!(e.value));
}
if (_googleMapState.widget.onCameraIdle != null) {
GoogleMapsFlutterPlatform.instance
.onCameraIdle(mapId: mapId)
.listen((_) => _googleMapState.widget.onCameraIdle!());
}
GoogleMapsFlutterPlatform.instance
.onMarkerTap(mapId: mapId)
.listen((MarkerTapEvent e) => _googleMapState.onMarkerTap(e.value));
GoogleMapsFlutterPlatform.instance.onMarkerDragStart(mapId: mapId).listen(
(MarkerDragStartEvent e) =>
_googleMapState.onMarkerDragStart(e.value, e.position));
GoogleMapsFlutterPlatform.instance.onMarkerDrag(mapId: mapId).listen(
(MarkerDragEvent e) =>
_googleMapState.onMarkerDrag(e.value, e.position));
GoogleMapsFlutterPlatform.instance.onMarkerDragEnd(mapId: mapId).listen(
(MarkerDragEndEvent e) =>
_googleMapState.onMarkerDragEnd(e.value, e.position));
GoogleMapsFlutterPlatform.instance.onInfoWindowTap(mapId: mapId).listen(
(InfoWindowTapEvent e) => _googleMapState.onInfoWindowTap(e.value));
GoogleMapsFlutterPlatform.instance
.onPolylineTap(mapId: mapId)
.listen((PolylineTapEvent e) => _googleMapState.onPolylineTap(e.value));
GoogleMapsFlutterPlatform.instance
.onPolygonTap(mapId: mapId)
.listen((PolygonTapEvent e) => _googleMapState.onPolygonTap(e.value));
GoogleMapsFlutterPlatform.instance
.onCircleTap(mapId: mapId)
.listen((CircleTapEvent e) => _googleMapState.onCircleTap(e.value));
GoogleMapsFlutterPlatform.instance
.onTap(mapId: mapId)
.listen((MapTapEvent e) => _googleMapState.onTap(e.position));
GoogleMapsFlutterPlatform.instance.onLongPress(mapId: mapId).listen(
(MapLongPressEvent e) => _googleMapState.onLongPress(e.position));
}
/// Updates configuration options of the map user interface.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updateMapConfiguration(MapConfiguration update) {
return GoogleMapsFlutterPlatform.instance
.updateMapConfiguration(update, mapId: mapId);
}
/// Updates marker configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updateMarkers(MarkerUpdates markerUpdates) {
return GoogleMapsFlutterPlatform.instance
.updateMarkers(markerUpdates, mapId: mapId);
}
/// Updates polygon configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updatePolygons(PolygonUpdates polygonUpdates) {
return GoogleMapsFlutterPlatform.instance
.updatePolygons(polygonUpdates, mapId: mapId);
}
/// Updates polyline configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updatePolylines(PolylineUpdates polylineUpdates) {
return GoogleMapsFlutterPlatform.instance
.updatePolylines(polylineUpdates, mapId: mapId);
}
/// Updates circle configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updateCircles(CircleUpdates circleUpdates) {
return GoogleMapsFlutterPlatform.instance
.updateCircles(circleUpdates, mapId: mapId);
}
/// Updates tile overlays configuration.
///
/// Change listeners are notified once the update has been made on the
/// platform side.
///
/// The returned [Future] completes after listeners have been notified.
Future<void> _updateTileOverlays(Set<TileOverlay> newTileOverlays) {
return GoogleMapsFlutterPlatform.instance
.updateTileOverlays(newTileOverlays: newTileOverlays, mapId: mapId);
}
/// Clears the tile cache so that all tiles will be requested again from the
/// [TileProvider].
///
/// The current tiles from this tile overlay will also be
/// cleared from the map after calling this method. The API maintains a small
/// in-memory cache of tiles. If you want to cache tiles for longer, you
/// should implement an on-disk cache.
Future<void> clearTileCache(TileOverlayId tileOverlayId) async {
return GoogleMapsFlutterPlatform.instance
.clearTileCache(tileOverlayId, mapId: mapId);
}
/// Starts an animated change of the map camera position.
///
/// The returned [Future] completes after the change has been started on the
/// platform side.
Future<void> animateCamera(CameraUpdate cameraUpdate) {
return GoogleMapsFlutterPlatform.instance
.animateCamera(cameraUpdate, mapId: mapId);
}
/// Changes the map camera position.
///
/// The returned [Future] completes after the change has been made on the
/// platform side.
Future<void> moveCamera(CameraUpdate cameraUpdate) {
return GoogleMapsFlutterPlatform.instance
.moveCamera(cameraUpdate, mapId: mapId);
}
/// Sets the styling of the base map.
///
/// Set to `null` to clear any previous custom styling.
///
/// If problems were detected with the [mapStyle], including un-parsable
/// styling JSON, unrecognized feature type, unrecognized element type, or
/// invalid styler keys: [MapStyleException] is thrown and the current
/// style is left unchanged.
///
/// The style string can be generated using [map style tool](https://mapstyle.withgoogle.com/).
/// Also, refer [iOS](https://developers.google.com/maps/documentation/ios-sdk/style-reference)
/// and [Android](https://developers.google.com/maps/documentation/android-sdk/style-reference)
/// style reference for more information regarding the supported styles.
@Deprecated('Use GoogleMap.style instead.')
Future<void> setMapStyle(String? mapStyle) {
return GoogleMapsFlutterPlatform.instance
.setMapStyle(mapStyle, mapId: mapId);
}
/// Returns the last style error, if any.
Future<String?> getStyleError() {
return GoogleMapsFlutterPlatform.instance.getStyleError(mapId: mapId);
}
/// Return [LatLngBounds] defining the region that is visible in a map.
Future<LatLngBounds> getVisibleRegion() {
return GoogleMapsFlutterPlatform.instance.getVisibleRegion(mapId: mapId);
}
/// Return [ScreenCoordinate] of the [LatLng] in the current map view.
///
/// A projection is used to translate between on screen location and geographic coordinates.
/// Screen location is in screen pixels (not display pixels) with respect to the top left corner
/// of the map, not necessarily of the whole screen.
Future<ScreenCoordinate> getScreenCoordinate(LatLng latLng) {
return GoogleMapsFlutterPlatform.instance
.getScreenCoordinate(latLng, mapId: mapId);
}
/// Returns [LatLng] corresponding to the [ScreenCoordinate] in the current map view.
///
/// Returned [LatLng] corresponds to a screen location. The screen location is specified in screen
/// pixels (not display pixels) relative to the top left of the map, not top left of the whole screen.
Future<LatLng> getLatLng(ScreenCoordinate screenCoordinate) {
return GoogleMapsFlutterPlatform.instance
.getLatLng(screenCoordinate, mapId: mapId);
}
/// Programmatically show the Info Window for a [Marker].
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [hideMarkerInfoWindow] to hide the Info Window.
/// * [isMarkerInfoWindowShown] to check if the Info Window is showing.
Future<void> showMarkerInfoWindow(MarkerId markerId) {
return GoogleMapsFlutterPlatform.instance
.showMarkerInfoWindow(markerId, mapId: mapId);
}
/// Programmatically hide the Info Window for a [Marker].
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [showMarkerInfoWindow] to show the Info Window.
/// * [isMarkerInfoWindowShown] to check if the Info Window is showing.
Future<void> hideMarkerInfoWindow(MarkerId markerId) {
return GoogleMapsFlutterPlatform.instance
.hideMarkerInfoWindow(markerId, mapId: mapId);
}
/// Returns `true` when the [InfoWindow] is showing, `false` otherwise.
///
/// The `markerId` must match one of the markers on the map.
/// An invalid `markerId` triggers an "Invalid markerId" error.
///
/// * See also:
/// * [showMarkerInfoWindow] to show the Info Window.
/// * [hideMarkerInfoWindow] to hide the Info Window.
Future<bool> isMarkerInfoWindowShown(MarkerId markerId) {
return GoogleMapsFlutterPlatform.instance
.isMarkerInfoWindowShown(markerId, mapId: mapId);
}
/// Returns the current zoom level of the map
Future<double> getZoomLevel() {
return GoogleMapsFlutterPlatform.instance.getZoomLevel(mapId: mapId);
}
/// Returns the image bytes of the map
Future<Uint8List?> takeSnapshot() {
return GoogleMapsFlutterPlatform.instance.takeSnapshot(mapId: mapId);
}
/// Disposes of the platform resources
void dispose() {
GoogleMapsFlutterPlatform.instance.dispose(mapId: mapId);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter/lib/src/controller.dart",
"repo_id": "packages",
"token_count": 3553
} | 1,064 |
rootProject.name = 'google_maps_flutter_android'
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/settings.gradle/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/settings.gradle",
"repo_id": "packages",
"token_count": 16
} | 1,065 |
// 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.BitmapDescriptor;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
/** Controller of a single Marker on the map. */
class MarkerController implements MarkerOptionsSink {
private final Marker marker;
private final String googleMapsMarkerId;
private boolean consumeTapEvents;
MarkerController(Marker marker, boolean consumeTapEvents) {
this.marker = marker;
this.consumeTapEvents = consumeTapEvents;
this.googleMapsMarkerId = marker.getId();
}
void remove() {
marker.remove();
}
@Override
public void setAlpha(float alpha) {
marker.setAlpha(alpha);
}
@Override
public void setAnchor(float u, float v) {
marker.setAnchor(u, v);
}
@Override
public void setConsumeTapEvents(boolean consumeTapEvents) {
this.consumeTapEvents = consumeTapEvents;
}
@Override
public void setDraggable(boolean draggable) {
marker.setDraggable(draggable);
}
@Override
public void setFlat(boolean flat) {
marker.setFlat(flat);
}
@Override
public void setIcon(BitmapDescriptor bitmapDescriptor) {
marker.setIcon(bitmapDescriptor);
}
@Override
public void setInfoWindowAnchor(float u, float v) {
marker.setInfoWindowAnchor(u, v);
}
@Override
public void setInfoWindowText(String title, String snippet) {
marker.setTitle(title);
marker.setSnippet(snippet);
}
@Override
public void setPosition(LatLng position) {
marker.setPosition(position);
}
@Override
public void setRotation(float rotation) {
marker.setRotation(rotation);
}
@Override
public void setVisible(boolean visible) {
marker.setVisible(visible);
}
@Override
public void setZIndex(float zIndex) {
marker.setZIndex(zIndex);
}
String getGoogleMapsMarkerId() {
return googleMapsMarkerId;
}
boolean consumeTapEvents() {
return consumeTapEvents;
}
public void showInfoWindow() {
marker.showInfoWindow();
}
public void hideInfoWindow() {
marker.hideInfoWindow();
}
public boolean isInfoWindowShown() {
return marker.isInfoWindowShown();
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkerController.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/MarkerController.java",
"repo_id": "packages",
"token_count": 799
} | 1,066 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.googlemaps;
import static junit.framework.TestCase.assertEquals;
import com.google.android.gms.maps.model.CircleOptions;
import org.junit.Test;
public class CircleBuilderTest {
@Test
public void density_AppliesToStrokeWidth() {
final float density = 5;
final float strokeWidth = 3;
final CircleBuilder builder = new CircleBuilder(density);
builder.setStrokeWidth(strokeWidth);
final CircleOptions options = builder.build();
final float width = options.getStrokeWidth();
assertEquals(density * strokeWidth, width);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/CircleBuilderTest.java/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/CircleBuilderTest.java",
"repo_id": "packages",
"token_count": 226
} | 1,067 |
maps.key=SomeKeyHere
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/secrets.properties/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/secrets.properties",
"repo_id": "packages",
"token_count": 8
} | 1,068 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
final LatLngBounds sydneyBounds = LatLngBounds(
southwest: const LatLng(-34.022631, 150.620685),
northeast: const LatLng(-33.571835, 151.325952),
);
class MapUiPage extends GoogleMapExampleAppPage {
const MapUiPage({Key? key})
: super(const Icon(Icons.map), 'User interface', key: key);
@override
Widget build(BuildContext context) {
return const MapUiBody();
}
}
class MapUiBody extends StatefulWidget {
const MapUiBody({super.key});
@override
State<StatefulWidget> createState() => MapUiBodyState();
}
class MapUiBodyState extends State<MapUiBody> {
MapUiBodyState();
static const CameraPosition _kInitialPosition = CameraPosition(
target: LatLng(-33.852, 151.211),
zoom: 11.0,
);
CameraPosition _position = _kInitialPosition;
bool _isMapCreated = false;
final bool _isMoving = false;
bool _compassEnabled = true;
bool _mapToolbarEnabled = true;
CameraTargetBounds _cameraTargetBounds = CameraTargetBounds.unbounded;
MinMaxZoomPreference _minMaxZoomPreference = MinMaxZoomPreference.unbounded;
MapType _mapType = MapType.normal;
bool _rotateGesturesEnabled = true;
bool _scrollGesturesEnabled = true;
bool _tiltGesturesEnabled = true;
bool _zoomControlsEnabled = false;
bool _zoomGesturesEnabled = true;
bool _indoorViewEnabled = true;
bool _myLocationEnabled = true;
bool _myTrafficEnabled = false;
bool _myLocationButtonEnabled = true;
late ExampleGoogleMapController _controller;
bool _nightMode = false;
String _mapStyle = '';
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
Widget _compassToggler() {
return TextButton(
child: Text('${_compassEnabled ? 'disable' : 'enable'} compass'),
onPressed: () {
setState(() {
_compassEnabled = !_compassEnabled;
});
},
);
}
Widget _mapToolbarToggler() {
return TextButton(
child: Text('${_mapToolbarEnabled ? 'disable' : 'enable'} map toolbar'),
onPressed: () {
setState(() {
_mapToolbarEnabled = !_mapToolbarEnabled;
});
},
);
}
Widget _latLngBoundsToggler() {
return TextButton(
child: Text(
_cameraTargetBounds.bounds == null
? 'bound camera target'
: 'release camera target',
),
onPressed: () {
setState(() {
_cameraTargetBounds = _cameraTargetBounds.bounds == null
? CameraTargetBounds(sydneyBounds)
: CameraTargetBounds.unbounded;
});
},
);
}
Widget _zoomBoundsToggler() {
return TextButton(
child: Text(_minMaxZoomPreference.minZoom == null
? 'bound zoom'
: 'release zoom'),
onPressed: () {
setState(() {
_minMaxZoomPreference = _minMaxZoomPreference.minZoom == null
? const MinMaxZoomPreference(12.0, 16.0)
: MinMaxZoomPreference.unbounded;
});
},
);
}
Widget _mapTypeCycler() {
final MapType nextType =
MapType.values[(_mapType.index + 1) % MapType.values.length];
return TextButton(
child: Text('change map type to $nextType'),
onPressed: () {
setState(() {
_mapType = nextType;
});
},
);
}
Widget _rotateToggler() {
return TextButton(
child: Text('${_rotateGesturesEnabled ? 'disable' : 'enable'} rotate'),
onPressed: () {
setState(() {
_rotateGesturesEnabled = !_rotateGesturesEnabled;
});
},
);
}
Widget _scrollToggler() {
return TextButton(
child: Text('${_scrollGesturesEnabled ? 'disable' : 'enable'} scroll'),
onPressed: () {
setState(() {
_scrollGesturesEnabled = !_scrollGesturesEnabled;
});
},
);
}
Widget _tiltToggler() {
return TextButton(
child: Text('${_tiltGesturesEnabled ? 'disable' : 'enable'} tilt'),
onPressed: () {
setState(() {
_tiltGesturesEnabled = !_tiltGesturesEnabled;
});
},
);
}
Widget _zoomToggler() {
return TextButton(
child: Text('${_zoomGesturesEnabled ? 'disable' : 'enable'} zoom'),
onPressed: () {
setState(() {
_zoomGesturesEnabled = !_zoomGesturesEnabled;
});
},
);
}
Widget _zoomControlsToggler() {
return TextButton(
child:
Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'),
onPressed: () {
setState(() {
_zoomControlsEnabled = !_zoomControlsEnabled;
});
},
);
}
Widget _indoorViewToggler() {
return TextButton(
child: Text('${_indoorViewEnabled ? 'disable' : 'enable'} indoor'),
onPressed: () {
setState(() {
_indoorViewEnabled = !_indoorViewEnabled;
});
},
);
}
Widget _myLocationToggler() {
return TextButton(
child: Text(
'${_myLocationEnabled ? 'disable' : 'enable'} my location marker'),
onPressed: () {
setState(() {
_myLocationEnabled = !_myLocationEnabled;
});
},
);
}
Widget _myLocationButtonToggler() {
return TextButton(
child: Text(
'${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'),
onPressed: () {
setState(() {
_myLocationButtonEnabled = !_myLocationButtonEnabled;
});
},
);
}
Widget _myTrafficToggler() {
return TextButton(
child: Text('${_myTrafficEnabled ? 'disable' : 'enable'} my traffic'),
onPressed: () {
setState(() {
_myTrafficEnabled = !_myTrafficEnabled;
});
},
);
}
Future<String> _getFileData(String path) async {
return rootBundle.loadString(path);
}
Widget _nightModeToggler() {
return TextButton(
child: Text('${_nightMode ? 'disable' : 'enable'} night mode'),
onPressed: () async {
_nightMode = !_nightMode;
final String style =
_nightMode ? await _getFileData('assets/night_mode.json') : '';
setState(() {
_mapStyle = style;
});
},
);
}
@override
Widget build(BuildContext context) {
final ExampleGoogleMap googleMap = ExampleGoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: _kInitialPosition,
compassEnabled: _compassEnabled,
mapToolbarEnabled: _mapToolbarEnabled,
cameraTargetBounds: _cameraTargetBounds,
minMaxZoomPreference: _minMaxZoomPreference,
mapType: _mapType,
style: _mapStyle,
rotateGesturesEnabled: _rotateGesturesEnabled,
scrollGesturesEnabled: _scrollGesturesEnabled,
tiltGesturesEnabled: _tiltGesturesEnabled,
zoomGesturesEnabled: _zoomGesturesEnabled,
zoomControlsEnabled: _zoomControlsEnabled,
indoorViewEnabled: _indoorViewEnabled,
myLocationEnabled: _myLocationEnabled,
myLocationButtonEnabled: _myLocationButtonEnabled,
trafficEnabled: _myTrafficEnabled,
onCameraMove: _updateCameraPosition,
);
final List<Widget> columnChildren = <Widget>[
Padding(
padding: const EdgeInsets.all(10.0),
child: Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: googleMap,
),
),
),
];
if (_isMapCreated) {
columnChildren.add(
Expanded(
child: ListView(
children: <Widget>[
Text('camera bearing: ${_position.bearing}'),
Text(
'camera target: ${_position.target.latitude.toStringAsFixed(4)},'
'${_position.target.longitude.toStringAsFixed(4)}'),
Text('camera zoom: ${_position.zoom}'),
Text('camera tilt: ${_position.tilt}'),
Text(_isMoving ? '(Camera moving)' : '(Camera idle)'),
_compassToggler(),
_mapToolbarToggler(),
_latLngBoundsToggler(),
_mapTypeCycler(),
_zoomBoundsToggler(),
_rotateToggler(),
_scrollToggler(),
_tiltToggler(),
_zoomToggler(),
_zoomControlsToggler(),
_indoorViewToggler(),
_myLocationToggler(),
_myLocationButtonToggler(),
_myTrafficToggler(),
_nightModeToggler(),
],
),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
);
}
void _updateCameraPosition(CameraPosition position) {
setState(() {
_position = position;
});
}
void onMapCreated(ExampleGoogleMapController controller) {
setState(() {
_controller = controller;
_isMapCreated = true;
});
// Log any style errors to the console for debugging.
_controller.getStyleError().then((String? error) {
if (error != null) {
debugPrint(error);
}
});
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/map_ui.dart",
"repo_id": "packages",
"token_count": 4192
} | 1,069 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
class AnimateCameraPage extends GoogleMapExampleAppPage {
const AnimateCameraPage({Key? key})
: super(const Icon(Icons.map), 'Camera control, animated', key: key);
@override
Widget build(BuildContext context) {
return const AnimateCamera();
}
}
class AnimateCamera extends StatefulWidget {
const AnimateCamera({super.key});
@override
State createState() => AnimateCameraState();
}
class AnimateCameraState extends State<AnimateCamera> {
ExampleGoogleMapController? mapController;
// ignore: use_setters_to_change_properties
void _onMapCreated(ExampleGoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: SizedBox(
width: 300.0,
height: 200.0,
child: ExampleGoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition:
const CameraPosition(target: LatLng(0.0, 0.0)),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: <Widget>[
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.newCameraPosition(
const CameraPosition(
bearing: 270.0,
target: LatLng(51.5160895, -0.1294527),
tilt: 30.0,
zoom: 17.0,
),
),
);
},
child: const Text('newCameraPosition'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.newLatLng(
const LatLng(56.1725505, 10.1850512),
),
);
},
child: const Text('newLatLng'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: const LatLng(-38.483935, 113.248673),
northeast: const LatLng(-8.982446, 153.823821),
),
10.0,
),
);
},
child: const Text('newLatLngBounds'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.newLatLngZoom(
const LatLng(37.4231613, -122.087159),
11.0,
),
);
},
child: const Text('newLatLngZoom'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.scrollBy(150.0, -225.0),
);
},
child: const Text('scrollBy'),
),
],
),
Column(
children: <Widget>[
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.zoomBy(
-0.5,
const Offset(30.0, 20.0),
),
);
},
child: const Text('zoomBy with focus'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.zoomBy(-0.5),
);
},
child: const Text('zoomBy'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.zoomIn(),
);
},
child: const Text('zoomIn'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.zoomOut(),
);
},
child: const Text('zoomOut'),
),
TextButton(
onPressed: () {
mapController?.animateCamera(
CameraUpdate.zoomTo(16.0),
);
},
child: const Text('zoomTo'),
),
],
),
],
)
],
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/animate_camera.dart",
"repo_id": "packages",
"token_count": 3309
} | 1,070 |
// 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/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'example_google_map.dart';
import 'page.dart';
const LatLng _center = LatLng(32.080664, 34.9563837);
class ScrollingMapPage extends GoogleMapExampleAppPage {
const ScrollingMapPage({Key? key})
: super(const Icon(Icons.map), 'Scrolling map', key: key);
@override
Widget build(BuildContext context) {
return const ScrollingMapBody();
}
}
class ScrollingMapBody extends StatelessWidget {
const ScrollingMapBody({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Card(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 30.0),
child: Column(
children: <Widget>[
const Padding(
padding: EdgeInsets.only(bottom: 12.0),
child: Text('This map consumes all touch events.'),
),
Center(
child: SizedBox(
width: 300.0,
height: 300.0,
child: ExampleGoogleMap(
initialCameraPosition: const CameraPosition(
target: _center,
zoom: 11.0,
),
gestureRecognizers: //
<Factory<OneSequenceGestureRecognizer>>{
Factory<OneSequenceGestureRecognizer>(
() => EagerGestureRecognizer(),
),
},
),
),
),
],
),
),
),
Card(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 30.0),
child: Column(
children: <Widget>[
const Text("This map doesn't consume the vertical drags."),
const Padding(
padding: EdgeInsets.only(bottom: 12.0),
child:
Text('It still gets other gestures (e.g scale or tap).'),
),
Center(
child: SizedBox(
width: 300.0,
height: 300.0,
child: ExampleGoogleMap(
initialCameraPosition: const CameraPosition(
target: _center,
zoom: 11.0,
),
markers: <Marker>{
Marker(
markerId: const MarkerId('test_marker_id'),
position: LatLng(
_center.latitude,
_center.longitude,
),
infoWindow: const InfoWindow(
title: 'An interesting location',
snippet: '*',
),
),
},
gestureRecognizers: <Factory<
OneSequenceGestureRecognizer>>{
Factory<OneSequenceGestureRecognizer>(
() => ScaleGestureRecognizer(),
),
},
),
),
),
],
),
),
),
],
);
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/shared/maps_example_dart/lib/scrolling_map.dart",
"repo_id": "packages",
"token_count": 2220
} | 1,071 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "GoogleMapController.h"
#import "FLTGoogleMapJSONConversions.h"
#import "FLTGoogleMapTileOverlayController.h"
#pragma mark - Conversion of JSON-like values sent via platform channels. Forward declarations.
@interface FLTGoogleMapFactory ()
@property(weak, nonatomic) NSObject<FlutterPluginRegistrar> *registrar;
@property(strong, nonatomic, readonly) id<NSObject> sharedMapServices;
@end
@implementation FLTGoogleMapFactory
@synthesize sharedMapServices = _sharedMapServices;
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_registrar = registrar;
}
return self;
}
- (NSObject<FlutterMessageCodec> *)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
// Precache shared map services, if needed.
// Retain the shared map services singleton, don't use the result for anything.
(void)[self sharedMapServices];
return [[FLTGoogleMapController alloc] initWithFrame:frame
viewIdentifier:viewId
arguments:args
registrar:self.registrar];
}
- (id<NSObject>)sharedMapServices {
if (_sharedMapServices == nil) {
// Calling this prepares GMSServices on a background thread controlled
// by the GoogleMaps framework.
// Retain the singleton to cache the initialization work across all map views.
_sharedMapServices = [GMSServices sharedServices];
}
return _sharedMapServices;
}
@end
@interface FLTGoogleMapController ()
@property(nonatomic, strong) GMSMapView *mapView;
@property(nonatomic, strong) FlutterMethodChannel *channel;
@property(nonatomic, assign) BOOL trackCameraPosition;
@property(nonatomic, weak) NSObject<FlutterPluginRegistrar> *registrar;
@property(nonatomic, strong) FLTMarkersController *markersController;
@property(nonatomic, strong) FLTPolygonsController *polygonsController;
@property(nonatomic, strong) FLTPolylinesController *polylinesController;
@property(nonatomic, strong) FLTCirclesController *circlesController;
@property(nonatomic, strong) FLTTileOverlaysController *tileOverlaysController;
// The resulting error message, if any, from the last attempt to set the map style.
// This is used to provide access to errors after the fact, since the map style is generally set at
// creation time and there's no mechanism to return non-fatal error details during platform view
// initialization.
@property(nonatomic, copy) NSString *styleError;
@end
@implementation FLTGoogleMapController
- (instancetype)initWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
GMSCameraPosition *camera =
[FLTGoogleMapJSONConversions cameraPostionFromDictionary:args[@"initialCameraPosition"]];
GMSMapView *mapView;
id mapID = nil;
NSString *cloudMapId = args[@"options"][@"cloudMapId"];
if (cloudMapId) {
Class mapIDClass = NSClassFromString(@"GMSMapID");
if (mapIDClass && [mapIDClass respondsToSelector:@selector(mapIDWithIdentifier:)]) {
mapID = [mapIDClass mapIDWithIdentifier:cloudMapId];
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// TODO(stuartmorgan): Switch to initWithOptions: once versions older than
// iOS 14 are no longer supported by the plugin, or there is a specific need
// for its functionality. Since it involves a newly-added class, call it
// dynamically is more trouble than it is currently worth.
if (mapID && [GMSMapView respondsToSelector:@selector(mapWithFrame:mapID:camera:)]) {
mapView = [GMSMapView mapWithFrame:frame mapID:mapID camera:camera];
} else {
mapView = [GMSMapView mapWithFrame:frame camera:camera];
}
#pragma clang diagnostic pop
return [self initWithMapView:mapView viewIdentifier:viewId arguments:args registrar:registrar];
}
- (instancetype)initWithMapView:(GMSMapView *_Nonnull)mapView
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
registrar:(NSObject<FlutterPluginRegistrar> *_Nonnull)registrar {
if (self = [super init]) {
_mapView = mapView;
_mapView.accessibilityElementsHidden = NO;
// TODO(cyanglaz): avoid sending message to self in the middle of the init method.
// https://github.com/flutter/flutter/issues/104121
[self interpretMapOptions:args[@"options"]];
NSString *channelName =
[NSString stringWithFormat:@"plugins.flutter.dev/google_maps_ios_%lld", viewId];
_channel = [FlutterMethodChannel methodChannelWithName:channelName
binaryMessenger:registrar.messenger];
__weak __typeof__(self) weakSelf = self;
[_channel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
if (weakSelf) {
[weakSelf onMethodCall:call result:result];
}
}];
_mapView.delegate = weakSelf;
_mapView.paddingAdjustmentBehavior = kGMSMapViewPaddingAdjustmentBehaviorNever;
_registrar = registrar;
_markersController = [[FLTMarkersController alloc] initWithMethodChannel:_channel
mapView:_mapView
registrar:registrar];
_polygonsController = [[FLTPolygonsController alloc] init:_channel
mapView:_mapView
registrar:registrar];
_polylinesController = [[FLTPolylinesController alloc] init:_channel
mapView:_mapView
registrar:registrar];
_circlesController = [[FLTCirclesController alloc] init:_channel
mapView:_mapView
registrar:registrar];
_tileOverlaysController = [[FLTTileOverlaysController alloc] init:_channel
mapView:_mapView
registrar:registrar];
id markersToAdd = args[@"markersToAdd"];
if ([markersToAdd isKindOfClass:[NSArray class]]) {
[_markersController addMarkers:markersToAdd];
}
id polygonsToAdd = args[@"polygonsToAdd"];
if ([polygonsToAdd isKindOfClass:[NSArray class]]) {
[_polygonsController addPolygons:polygonsToAdd];
}
id polylinesToAdd = args[@"polylinesToAdd"];
if ([polylinesToAdd isKindOfClass:[NSArray class]]) {
[_polylinesController addPolylines:polylinesToAdd];
}
id circlesToAdd = args[@"circlesToAdd"];
if ([circlesToAdd isKindOfClass:[NSArray class]]) {
[_circlesController addCircles:circlesToAdd];
}
id tileOverlaysToAdd = args[@"tileOverlaysToAdd"];
if ([tileOverlaysToAdd isKindOfClass:[NSArray class]]) {
[_tileOverlaysController addTileOverlays:tileOverlaysToAdd];
}
[_mapView addObserver:self forKeyPath:@"frame" options:0 context:nil];
}
return self;
}
- (UIView *)view {
return self.mapView;
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (object == self.mapView && [keyPath isEqualToString:@"frame"]) {
CGRect bounds = self.mapView.bounds;
if (CGRectEqualToRect(bounds, CGRectZero)) {
// The workaround is to fix an issue that the camera location is not current when
// the size of the map is zero at initialization.
// So We only care about the size of the `self.mapView`, ignore the frame changes when the
// size is zero.
return;
}
// We only observe the frame for initial setup.
[self.mapView removeObserver:self forKeyPath:@"frame"];
[self.mapView moveCamera:[GMSCameraUpdate setCamera:self.mapView.camera]];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)onMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
if ([call.method isEqualToString:@"map#show"]) {
[self showAtOrigin:CGPointMake([call.arguments[@"x"] doubleValue],
[call.arguments[@"y"] doubleValue])];
result(nil);
} else if ([call.method isEqualToString:@"map#hide"]) {
[self hide];
result(nil);
} else if ([call.method isEqualToString:@"camera#animate"]) {
[self
animateWithCameraUpdate:[FLTGoogleMapJSONConversions
cameraUpdateFromChannelValue:call.arguments[@"cameraUpdate"]]];
result(nil);
} else if ([call.method isEqualToString:@"camera#move"]) {
[self moveWithCameraUpdate:[FLTGoogleMapJSONConversions
cameraUpdateFromChannelValue:call.arguments[@"cameraUpdate"]]];
result(nil);
} else if ([call.method isEqualToString:@"map#update"]) {
[self interpretMapOptions:call.arguments[@"options"]];
result([FLTGoogleMapJSONConversions dictionaryFromPosition:[self cameraPosition]]);
} else if ([call.method isEqualToString:@"map#getVisibleRegion"]) {
if (self.mapView != nil) {
GMSVisibleRegion visibleRegion = self.mapView.projection.visibleRegion;
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithRegion:visibleRegion];
result([FLTGoogleMapJSONConversions dictionaryFromCoordinateBounds:bounds]);
} else {
result([FlutterError errorWithCode:@"GoogleMap uninitialized"
message:@"getVisibleRegion called prior to map initialization"
details:nil]);
}
} else if ([call.method isEqualToString:@"map#getScreenCoordinate"]) {
if (self.mapView != nil) {
CLLocationCoordinate2D location =
[FLTGoogleMapJSONConversions locationFromLatLong:call.arguments];
CGPoint point = [self.mapView.projection pointForCoordinate:location];
result([FLTGoogleMapJSONConversions dictionaryFromPoint:point]);
} else {
result([FlutterError errorWithCode:@"GoogleMap uninitialized"
message:@"getScreenCoordinate called prior to map initialization"
details:nil]);
}
} else if ([call.method isEqualToString:@"map#getLatLng"]) {
if (self.mapView != nil && call.arguments) {
CGPoint point = [FLTGoogleMapJSONConversions pointFromDictionary:call.arguments];
CLLocationCoordinate2D latlng = [self.mapView.projection coordinateForPoint:point];
result([FLTGoogleMapJSONConversions arrayFromLocation:latlng]);
} else {
result([FlutterError errorWithCode:@"GoogleMap uninitialized"
message:@"getLatLng called prior to map initialization"
details:nil]);
}
} else if ([call.method isEqualToString:@"map#waitForMap"]) {
result(nil);
} else if ([call.method isEqualToString:@"map#takeSnapshot"]) {
if (self.mapView != nil) {
UIGraphicsImageRenderer *renderer =
[[UIGraphicsImageRenderer alloc] initWithSize:self.mapView.bounds.size];
// For some unknown reason mapView.layer::renderInContext API returns a blank image on iOS 17.
// So we have to use drawViewHierarchyInRect API.
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
[self.mapView drawViewHierarchyInRect:self.mapView.bounds afterScreenUpdates:YES];
}];
result([FlutterStandardTypedData typedDataWithBytes:UIImagePNGRepresentation(image)]);
} else {
result([FlutterError errorWithCode:@"GoogleMap uninitialized"
message:@"takeSnapshot called prior to map initialization"
details:nil]);
}
} else if ([call.method isEqualToString:@"markers#update"]) {
id markersToAdd = call.arguments[@"markersToAdd"];
if ([markersToAdd isKindOfClass:[NSArray class]]) {
[self.markersController addMarkers:markersToAdd];
}
id markersToChange = call.arguments[@"markersToChange"];
if ([markersToChange isKindOfClass:[NSArray class]]) {
[self.markersController changeMarkers:markersToChange];
}
id markerIdsToRemove = call.arguments[@"markerIdsToRemove"];
if ([markerIdsToRemove isKindOfClass:[NSArray class]]) {
[self.markersController removeMarkersWithIdentifiers:markerIdsToRemove];
}
result(nil);
} else if ([call.method isEqualToString:@"markers#showInfoWindow"]) {
id markerId = call.arguments[@"markerId"];
if ([markerId isKindOfClass:[NSString class]]) {
[self.markersController showMarkerInfoWindowWithIdentifier:markerId result:result];
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"showInfoWindow called with invalid markerId"
details:nil]);
}
} else if ([call.method isEqualToString:@"markers#hideInfoWindow"]) {
id markerId = call.arguments[@"markerId"];
if ([markerId isKindOfClass:[NSString class]]) {
[self.markersController hideMarkerInfoWindowWithIdentifier:markerId result:result];
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"hideInfoWindow called with invalid markerId"
details:nil]);
}
} else if ([call.method isEqualToString:@"markers#isInfoWindowShown"]) {
id markerId = call.arguments[@"markerId"];
if ([markerId isKindOfClass:[NSString class]]) {
[self.markersController isInfoWindowShownForMarkerWithIdentifier:markerId result:result];
} else {
result([FlutterError errorWithCode:@"Invalid markerId"
message:@"isInfoWindowShown called with invalid markerId"
details:nil]);
}
} else if ([call.method isEqualToString:@"polygons#update"]) {
id polygonsToAdd = call.arguments[@"polygonsToAdd"];
if ([polygonsToAdd isKindOfClass:[NSArray class]]) {
[self.polygonsController addPolygons:polygonsToAdd];
}
id polygonsToChange = call.arguments[@"polygonsToChange"];
if ([polygonsToChange isKindOfClass:[NSArray class]]) {
[self.polygonsController changePolygons:polygonsToChange];
}
id polygonIdsToRemove = call.arguments[@"polygonIdsToRemove"];
if ([polygonIdsToRemove isKindOfClass:[NSArray class]]) {
[self.polygonsController removePolygonWithIdentifiers:polygonIdsToRemove];
}
result(nil);
} else if ([call.method isEqualToString:@"polylines#update"]) {
id polylinesToAdd = call.arguments[@"polylinesToAdd"];
if ([polylinesToAdd isKindOfClass:[NSArray class]]) {
[self.polylinesController addPolylines:polylinesToAdd];
}
id polylinesToChange = call.arguments[@"polylinesToChange"];
if ([polylinesToChange isKindOfClass:[NSArray class]]) {
[self.polylinesController changePolylines:polylinesToChange];
}
id polylineIdsToRemove = call.arguments[@"polylineIdsToRemove"];
if ([polylineIdsToRemove isKindOfClass:[NSArray class]]) {
[self.polylinesController removePolylineWithIdentifiers:polylineIdsToRemove];
}
result(nil);
} else if ([call.method isEqualToString:@"circles#update"]) {
id circlesToAdd = call.arguments[@"circlesToAdd"];
if ([circlesToAdd isKindOfClass:[NSArray class]]) {
[self.circlesController addCircles:circlesToAdd];
}
id circlesToChange = call.arguments[@"circlesToChange"];
if ([circlesToChange isKindOfClass:[NSArray class]]) {
[self.circlesController changeCircles:circlesToChange];
}
id circleIdsToRemove = call.arguments[@"circleIdsToRemove"];
if ([circleIdsToRemove isKindOfClass:[NSArray class]]) {
[self.circlesController removeCircleWithIdentifiers:circleIdsToRemove];
}
result(nil);
} else if ([call.method isEqualToString:@"tileOverlays#update"]) {
id tileOverlaysToAdd = call.arguments[@"tileOverlaysToAdd"];
if ([tileOverlaysToAdd isKindOfClass:[NSArray class]]) {
[self.tileOverlaysController addTileOverlays:tileOverlaysToAdd];
}
id tileOverlaysToChange = call.arguments[@"tileOverlaysToChange"];
if ([tileOverlaysToChange isKindOfClass:[NSArray class]]) {
[self.tileOverlaysController changeTileOverlays:tileOverlaysToChange];
}
id tileOverlayIdsToRemove = call.arguments[@"tileOverlayIdsToRemove"];
if ([tileOverlayIdsToRemove isKindOfClass:[NSArray class]]) {
[self.tileOverlaysController removeTileOverlayWithIdentifiers:tileOverlayIdsToRemove];
}
result(nil);
} else if ([call.method isEqualToString:@"tileOverlays#clearTileCache"]) {
id rawTileOverlayId = call.arguments[@"tileOverlayId"];
[self.tileOverlaysController clearTileCacheWithIdentifier:rawTileOverlayId];
result(nil);
} else if ([call.method isEqualToString:@"map#isCompassEnabled"]) {
NSNumber *isCompassEnabled = @(self.mapView.settings.compassButton);
result(isCompassEnabled);
} else if ([call.method isEqualToString:@"map#isMapToolbarEnabled"]) {
NSNumber *isMapToolbarEnabled = @NO;
result(isMapToolbarEnabled);
} else if ([call.method isEqualToString:@"map#getMinMaxZoomLevels"]) {
NSArray *zoomLevels = @[ @(self.mapView.minZoom), @(self.mapView.maxZoom) ];
result(zoomLevels);
} else if ([call.method isEqualToString:@"map#getZoomLevel"]) {
result(@(self.mapView.camera.zoom));
} else if ([call.method isEqualToString:@"map#isZoomGesturesEnabled"]) {
NSNumber *isZoomGesturesEnabled = @(self.mapView.settings.zoomGestures);
result(isZoomGesturesEnabled);
} else if ([call.method isEqualToString:@"map#isZoomControlsEnabled"]) {
NSNumber *isZoomControlsEnabled = @NO;
result(isZoomControlsEnabled);
} else if ([call.method isEqualToString:@"map#isTiltGesturesEnabled"]) {
NSNumber *isTiltGesturesEnabled = @(self.mapView.settings.tiltGestures);
result(isTiltGesturesEnabled);
} else if ([call.method isEqualToString:@"map#isRotateGesturesEnabled"]) {
NSNumber *isRotateGesturesEnabled = @(self.mapView.settings.rotateGestures);
result(isRotateGesturesEnabled);
} else if ([call.method isEqualToString:@"map#isScrollGesturesEnabled"]) {
NSNumber *isScrollGesturesEnabled = @(self.mapView.settings.scrollGestures);
result(isScrollGesturesEnabled);
} else if ([call.method isEqualToString:@"map#isMyLocationButtonEnabled"]) {
NSNumber *isMyLocationButtonEnabled = @(self.mapView.settings.myLocationButton);
result(isMyLocationButtonEnabled);
} else if ([call.method isEqualToString:@"map#isTrafficEnabled"]) {
NSNumber *isTrafficEnabled = @(self.mapView.trafficEnabled);
result(isTrafficEnabled);
} else if ([call.method isEqualToString:@"map#isBuildingsEnabled"]) {
NSNumber *isBuildingsEnabled = @(self.mapView.buildingsEnabled);
result(isBuildingsEnabled);
} else if ([call.method isEqualToString:@"map#setStyle"]) {
id mapStyle = [call arguments];
self.styleError = [self setMapStyle:(mapStyle == [NSNull null] ? nil : mapStyle)];
if (self.styleError == nil) {
result(@[ @(YES) ]);
} else {
result(@[ @(NO), self.styleError ]);
}
} else if ([call.method isEqualToString:@"map#getStyleError"]) {
result(self.styleError);
} else if ([call.method isEqualToString:@"map#getTileOverlayInfo"]) {
NSString *rawTileOverlayId = call.arguments[@"tileOverlayId"];
result([self.tileOverlaysController tileOverlayInfoWithIdentifier:rawTileOverlayId]);
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)showAtOrigin:(CGPoint)origin {
CGRect frame = {origin, self.mapView.frame.size};
self.mapView.frame = frame;
self.mapView.hidden = NO;
}
- (void)hide {
self.mapView.hidden = YES;
}
- (void)animateWithCameraUpdate:(GMSCameraUpdate *)cameraUpdate {
[self.mapView animateWithCameraUpdate:cameraUpdate];
}
- (void)moveWithCameraUpdate:(GMSCameraUpdate *)cameraUpdate {
[self.mapView moveCamera:cameraUpdate];
}
- (GMSCameraPosition *)cameraPosition {
if (self.trackCameraPosition) {
return self.mapView.camera;
} else {
return nil;
}
}
- (void)setCamera:(GMSCameraPosition *)camera {
self.mapView.camera = camera;
}
- (void)setCameraTargetBounds:(GMSCoordinateBounds *)bounds {
self.mapView.cameraTargetBounds = bounds;
}
- (void)setCompassEnabled:(BOOL)enabled {
self.mapView.settings.compassButton = enabled;
}
- (void)setIndoorEnabled:(BOOL)enabled {
self.mapView.indoorEnabled = enabled;
}
- (void)setTrafficEnabled:(BOOL)enabled {
self.mapView.trafficEnabled = enabled;
}
- (void)setBuildingsEnabled:(BOOL)enabled {
self.mapView.buildingsEnabled = enabled;
}
- (void)setMapType:(GMSMapViewType)mapType {
self.mapView.mapType = mapType;
}
- (void)setMinZoom:(float)minZoom maxZoom:(float)maxZoom {
[self.mapView setMinZoom:minZoom maxZoom:maxZoom];
}
- (void)setPaddingTop:(float)top left:(float)left bottom:(float)bottom right:(float)right {
self.mapView.padding = UIEdgeInsetsMake(top, left, bottom, right);
}
- (void)setRotateGesturesEnabled:(BOOL)enabled {
self.mapView.settings.rotateGestures = enabled;
}
- (void)setScrollGesturesEnabled:(BOOL)enabled {
self.mapView.settings.scrollGestures = enabled;
}
- (void)setTiltGesturesEnabled:(BOOL)enabled {
self.mapView.settings.tiltGestures = enabled;
}
- (void)setTrackCameraPosition:(BOOL)enabled {
_trackCameraPosition = enabled;
}
- (void)setZoomGesturesEnabled:(BOOL)enabled {
self.mapView.settings.zoomGestures = enabled;
}
- (void)setMyLocationEnabled:(BOOL)enabled {
self.mapView.myLocationEnabled = enabled;
}
- (void)setMyLocationButtonEnabled:(BOOL)enabled {
self.mapView.settings.myLocationButton = enabled;
}
- (NSString *)setMapStyle:(NSString *)mapStyle {
if (mapStyle.length == 0) {
self.mapView.mapStyle = nil;
return nil;
}
NSError *error;
GMSMapStyle *style = [GMSMapStyle styleWithJSONString:mapStyle error:&error];
if (!style) {
return [error localizedDescription];
} else {
self.mapView.mapStyle = style;
return nil;
}
}
#pragma mark - GMSMapViewDelegate methods
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
[self.channel invokeMethod:@"camera#onMoveStarted" arguments:@{@"isGesture" : @(gesture)}];
}
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
if (self.trackCameraPosition) {
[self.channel invokeMethod:@"camera#onMove"
arguments:@{
@"position" : [FLTGoogleMapJSONConversions dictionaryFromPosition:position]
}];
}
}
- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position {
[self.channel invokeMethod:@"camera#onIdle" arguments:@{}];
}
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
NSString *markerId = marker.userData[0];
return [self.markersController didTapMarkerWithIdentifier:markerId];
}
- (void)mapView:(GMSMapView *)mapView didEndDraggingMarker:(GMSMarker *)marker {
NSString *markerId = marker.userData[0];
[self.markersController didEndDraggingMarkerWithIdentifier:markerId location:marker.position];
}
- (void)mapView:(GMSMapView *)mapView didBeginDraggingMarker:(GMSMarker *)marker {
NSString *markerId = marker.userData[0];
[self.markersController didStartDraggingMarkerWithIdentifier:markerId location:marker.position];
}
- (void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker {
NSString *markerId = marker.userData[0];
[self.markersController didDragMarkerWithIdentifier:markerId location:marker.position];
}
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
NSString *markerId = marker.userData[0];
[self.markersController didTapInfoWindowOfMarkerWithIdentifier:markerId];
}
- (void)mapView:(GMSMapView *)mapView didTapOverlay:(GMSOverlay *)overlay {
NSString *overlayId = overlay.userData[0];
if ([self.polylinesController hasPolylineWithIdentifier:overlayId]) {
[self.polylinesController didTapPolylineWithIdentifier:overlayId];
} else if ([self.polygonsController hasPolygonWithIdentifier:overlayId]) {
[self.polygonsController didTapPolygonWithIdentifier:overlayId];
} else if ([self.circlesController hasCircleWithIdentifier:overlayId]) {
[self.circlesController didTapCircleWithIdentifier:overlayId];
}
}
- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
[self.channel
invokeMethod:@"map#onTap"
arguments:@{@"position" : [FLTGoogleMapJSONConversions arrayFromLocation:coordinate]}];
}
- (void)mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate {
[self.channel
invokeMethod:@"map#onLongPress"
arguments:@{@"position" : [FLTGoogleMapJSONConversions arrayFromLocation:coordinate]}];
}
- (void)interpretMapOptions:(NSDictionary *)data {
NSArray *cameraTargetBounds = data[@"cameraTargetBounds"];
if (cameraTargetBounds && cameraTargetBounds != (id)[NSNull null]) {
[self
setCameraTargetBounds:cameraTargetBounds.count > 0 && cameraTargetBounds[0] != [NSNull null]
? [FLTGoogleMapJSONConversions
coordinateBoundsFromLatLongs:cameraTargetBounds.firstObject]
: nil];
}
NSNumber *compassEnabled = data[@"compassEnabled"];
if (compassEnabled && compassEnabled != (id)[NSNull null]) {
[self setCompassEnabled:[compassEnabled boolValue]];
}
id indoorEnabled = data[@"indoorEnabled"];
if (indoorEnabled && indoorEnabled != [NSNull null]) {
[self setIndoorEnabled:[indoorEnabled boolValue]];
}
id trafficEnabled = data[@"trafficEnabled"];
if (trafficEnabled && trafficEnabled != [NSNull null]) {
[self setTrafficEnabled:[trafficEnabled boolValue]];
}
id buildingsEnabled = data[@"buildingsEnabled"];
if (buildingsEnabled && buildingsEnabled != [NSNull null]) {
[self setBuildingsEnabled:[buildingsEnabled boolValue]];
}
id mapType = data[@"mapType"];
if (mapType && mapType != [NSNull null]) {
[self setMapType:[FLTGoogleMapJSONConversions mapViewTypeFromTypeValue:mapType]];
}
NSArray *zoomData = data[@"minMaxZoomPreference"];
if (zoomData && zoomData != (id)[NSNull null]) {
float minZoom = (zoomData[0] == [NSNull null]) ? kGMSMinZoomLevel : [zoomData[0] floatValue];
float maxZoom = (zoomData[1] == [NSNull null]) ? kGMSMaxZoomLevel : [zoomData[1] floatValue];
[self setMinZoom:minZoom maxZoom:maxZoom];
}
NSArray *paddingData = data[@"padding"];
if (paddingData) {
float top = (paddingData[0] == [NSNull null]) ? 0 : [paddingData[0] floatValue];
float left = (paddingData[1] == [NSNull null]) ? 0 : [paddingData[1] floatValue];
float bottom = (paddingData[2] == [NSNull null]) ? 0 : [paddingData[2] floatValue];
float right = (paddingData[3] == [NSNull null]) ? 0 : [paddingData[3] floatValue];
[self setPaddingTop:top left:left bottom:bottom right:right];
}
NSNumber *rotateGesturesEnabled = data[@"rotateGesturesEnabled"];
if (rotateGesturesEnabled && rotateGesturesEnabled != (id)[NSNull null]) {
[self setRotateGesturesEnabled:[rotateGesturesEnabled boolValue]];
}
NSNumber *scrollGesturesEnabled = data[@"scrollGesturesEnabled"];
if (scrollGesturesEnabled && scrollGesturesEnabled != (id)[NSNull null]) {
[self setScrollGesturesEnabled:[scrollGesturesEnabled boolValue]];
}
NSNumber *tiltGesturesEnabled = data[@"tiltGesturesEnabled"];
if (tiltGesturesEnabled && tiltGesturesEnabled != (id)[NSNull null]) {
[self setTiltGesturesEnabled:[tiltGesturesEnabled boolValue]];
}
NSNumber *trackCameraPosition = data[@"trackCameraPosition"];
if (trackCameraPosition && trackCameraPosition != (id)[NSNull null]) {
[self setTrackCameraPosition:[trackCameraPosition boolValue]];
}
NSNumber *zoomGesturesEnabled = data[@"zoomGesturesEnabled"];
if (zoomGesturesEnabled && zoomGesturesEnabled != (id)[NSNull null]) {
[self setZoomGesturesEnabled:[zoomGesturesEnabled boolValue]];
}
NSNumber *myLocationEnabled = data[@"myLocationEnabled"];
if (myLocationEnabled && myLocationEnabled != (id)[NSNull null]) {
[self setMyLocationEnabled:[myLocationEnabled boolValue]];
}
NSNumber *myLocationButtonEnabled = data[@"myLocationButtonEnabled"];
if (myLocationButtonEnabled && myLocationButtonEnabled != (id)[NSNull null]) {
[self setMyLocationButtonEnabled:[myLocationButtonEnabled boolValue]];
}
NSString *style = data[@"style"];
if (style) {
self.styleError = [self setMapStyle:style];
}
}
@end
| packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapController.m/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapController.m",
"repo_id": "packages",
"token_count": 11472
} | 1,072 |
// 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, listEquals, objectRuntimeType;
import 'types.dart';
/// A cluster containing multiple markers.
@immutable
class Cluster {
/// Creates a cluster with its location [LatLng], bounds [LatLngBounds],
/// and list of [MarkerId]s in the cluster.
const Cluster(
this.clusterManagerId,
this.markerIds, {
required this.position,
required this.bounds,
}) : assert(markerIds.length > 0);
/// ID of the [ClusterManager] of the cluster.
final ClusterManagerId clusterManagerId;
/// Cluster marker location.
final LatLng position;
/// The bounds containing all cluster markers.
final LatLngBounds bounds;
/// List of [MarkerId]s in the cluster.
final List<MarkerId> markerIds;
/// Returns the number of markers in the cluster.
int get count => markerIds.length;
@override
String toString() =>
'${objectRuntimeType(this, 'Cluster')}($clusterManagerId, $position, $bounds, $markerIds)';
@override
bool operator ==(Object other) {
return other is Cluster &&
other.clusterManagerId == clusterManagerId &&
other.position == position &&
other.bounds == bounds &&
listEquals(other.markerIds, markerIds);
}
@override
int get hashCode =>
Object.hash(clusterManagerId, position, bounds, markerIds);
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/cluster.dart",
"repo_id": "packages",
"token_count": 494
} | 1,073 |
// 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';
/// [Polyline] update events to be applied to the [GoogleMap].
///
/// Used in [GoogleMapController] when the map is updated.
// (Do not re-export)
class PolylineUpdates extends MapsObjectUpdates<Polyline> {
/// Computes [PolylineUpdates] given previous and current [Polyline]s.
PolylineUpdates.from(super.previous, super.current)
: super.from(objectName: 'polyline');
/// Set of Polylines to be added in this update.
Set<Polyline> get polylinesToAdd => objectsToAdd;
/// Set of PolylineIds to be removed in this update.
Set<PolylineId> get polylineIdsToRemove =>
objectIdsToRemove.cast<PolylineId>();
/// Set of Polylines to be changed in this update.
Set<Polyline> get polylinesToChange => objectsToChange;
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/polyline_updates.dart",
"repo_id": "packages",
"token_count": 282
} | 1,074 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// This setting controls how the API handles gestures on the map
enum WebGestureHandling {
/// Scroll events and one-finger touch gestures scroll the page, and do not
/// zoom or pan the map. Two-finger touch gestures pan and zoom the map.
/// Scroll events with a ctrl key or β key pressed zoom the map. In this mode
/// the map cooperates with the page.
cooperative,
/// All touch gestures and scroll events pan or zoom the map.
greedy,
/// The map cannot be panned or zoomed by user gestures.
none,
/// (default) Gesture handling is either cooperative or greedy, depending on
/// whether the page is scrollable or in an iframe.
auto,
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/web_gesture_handling.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/web_gesture_handling.dart",
"repo_id": "packages",
"token_count": 217
} | 1,075 |
// 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/src/types/tile_overlay.dart';
import 'package:google_maps_flutter_platform_interface/src/types/tile_overlay_updates.dart';
import 'package:google_maps_flutter_platform_interface/src/types/utils/tile_overlay.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('tile overlay updates tests', () {
test('Correctly set toRemove, toAdd and toChange', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
final Set<TileOverlayId> toRemove = <TileOverlayId>{
const TileOverlayId('id1')
};
expect(updates.tileOverlayIdsToRemove, toRemove);
final Set<TileOverlay> toAdd = <TileOverlay>{to4};
expect(updates.tileOverlaysToAdd, toAdd);
final Set<TileOverlay> toChange = <TileOverlay>{to3Changed};
expect(updates.tileOverlaysToChange, toChange);
});
test('toJson', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
final Object json = updates.toJson();
expect(json, <String, Object>{
'tileOverlaysToAdd': serializeTileOverlaySet(updates.tileOverlaysToAdd),
'tileOverlaysToChange':
serializeTileOverlaySet(updates.tileOverlaysToChange),
'tileOverlayIdsToRemove': updates.tileOverlayIdsToRemove
.map<String>((TileOverlayId m) => m.value)
.toList()
});
});
test('equality', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current1 = <TileOverlay>{to2, to3Changed, to4};
final Set<TileOverlay> current2 = <TileOverlay>{to2, to3Changed, to4};
final Set<TileOverlay> current3 = <TileOverlay>{to2, to4};
final TileOverlayUpdates updates1 =
TileOverlayUpdates.from(previous, current1);
final TileOverlayUpdates updates2 =
TileOverlayUpdates.from(previous, current2);
final TileOverlayUpdates updates3 =
TileOverlayUpdates.from(previous, current3);
expect(updates1, updates2);
expect(updates1, isNot(updates3));
});
test('hashCode', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
expect(
updates.hashCode,
Object.hash(
Object.hashAll(updates.tileOverlaysToAdd),
Object.hashAll(updates.tileOverlayIdsToRemove),
Object.hashAll(updates.tileOverlaysToChange)));
});
test('toString', () async {
const TileOverlay to1 = TileOverlay(tileOverlayId: TileOverlayId('id1'));
const TileOverlay to2 = TileOverlay(tileOverlayId: TileOverlayId('id2'));
const TileOverlay to3 = TileOverlay(tileOverlayId: TileOverlayId('id3'));
const TileOverlay to3Changed =
TileOverlay(tileOverlayId: TileOverlayId('id3'), transparency: 0.5);
const TileOverlay to4 = TileOverlay(tileOverlayId: TileOverlayId('id4'));
final Set<TileOverlay> previous = <TileOverlay>{to1, to2, to3};
final Set<TileOverlay> current = <TileOverlay>{to2, to3Changed, to4};
final TileOverlayUpdates updates =
TileOverlayUpdates.from(previous, current);
expect(
updates.toString(),
'TileOverlayUpdates(add: ${updates.tileOverlaysToAdd}, '
'remove: ${updates.tileOverlayIdsToRemove}, '
'change: ${updates.tileOverlaysToChange})');
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/tile_overlay_updates_test.dart",
"repo_id": "packages",
"token_count": 2382
} | 1,076 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:js_interop';
import 'package:flutter_test/flutter_test.dart';
import 'package:google_maps/google_maps.dart' as gmaps;
import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart';
import 'package:google_maps_flutter_web/google_maps_flutter_web.dart';
import 'package:integration_test/integration_test.dart';
import 'package:web/web.dart';
import 'resources/tile16_base64.dart';
class NoTileProvider implements TileProvider {
const NoTileProvider();
@override
Future<Tile> getTile(int x, int y, int? zoom) async => TileProvider.noTile;
}
class TestTileProvider implements TileProvider {
const TestTileProvider();
@override
Future<Tile> getTile(int x, int y, int? zoom) async =>
Tile(16, 16, const Base64Decoder().convert(tile16Base64));
}
/// Test Overlays
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('TileOverlayController', () {
const TileOverlayId id = TileOverlayId('');
testWidgets('minimal initialization', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(tileOverlayId: id),
);
final gmaps.Size size = controller.gmMapType.tileSize!;
expect(size.width, TileOverlayController.logicalTileSize);
expect(size.height, TileOverlayController.logicalTileSize);
expect(
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, document),
null,
);
});
testWidgets('produces image tiles', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(
tileOverlayId: id,
tileProvider: TestTileProvider(),
),
);
final HTMLImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, document)!
as HTMLImageElement;
expect(img.naturalWidth, 0);
expect(img.naturalHeight, 0);
expect(img.hidden, true);
await img.onLoad.first;
await img.decode().toDart;
expect(img.hidden, false);
expect(img.naturalWidth, 16);
expect(img.naturalHeight, 16);
});
testWidgets('update', (WidgetTester tester) async {
final TileOverlayController controller = TileOverlayController(
tileOverlay: const TileOverlay(
tileOverlayId: id,
tileProvider: NoTileProvider(),
),
);
{
final HTMLImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, document)!
as HTMLImageElement;
await null; // let `getTile` `then` complete
expect(
img.src,
isEmpty,
reason: 'The NoTileProvider never updates the img src',
);
}
controller.update(const TileOverlay(
tileOverlayId: id,
tileProvider: TestTileProvider(),
));
{
final HTMLImageElement img =
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, document)!
as HTMLImageElement;
await img.onLoad.first;
expect(
img.src,
isNotEmpty,
reason: 'The img `src` should eventually become the Blob URL.',
);
}
controller.update(const TileOverlay(tileOverlayId: id));
{
expect(
controller.gmMapType.getTile!(gmaps.Point(0, 0), 0, document),
null,
reason: 'Setting a null tileProvider should work.',
);
}
});
});
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/example/integration_test/overlay_test.dart",
"repo_id": "packages",
"token_count": 1512
} | 1,077 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// TODO(srujzs): Needed for https://github.com/dart-lang/sdk/issues/54801. Once
// we publish a version with a min SDK constraint that contains this fix,
// remove.
@JS()
library;
import 'dart:js_interop';
import 'package:web/web.dart' as web;
/// This extension gives [web.Window] a nullable getter to the `trustedTypes`
/// property, which is used to check for feature support.
extension NullableTrustedTypesGetter on web.Window {
/// (Nullable) Bindings to window.trustedTypes.
///
/// This may be null if the browser doesn't support the Trusted Types API.
///
/// See: https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
@JS('trustedTypes')
external web.TrustedTypePolicyFactory? get nullableTrustedTypes;
}
/// This extension provides a setter for the [web.HTMLElement] `innerHTML` property,
/// that accepts trusted HTML only.
extension TrustedInnerHTML on web.HTMLElement {
/// Set the inner HTML of this element to the given [trustedHTML].
@JS('innerHTML')
external set trustedInnerHTML(web.TrustedHTML trustedHTML);
}
/// Allows creating a TrustedHTML object from a string, with no arguments.
extension CreateHTMLNoArgs on web.TrustedTypePolicy {
/// Allows calling `createHTML` with only the `input` argument.
@JS('createHTML')
external web.TrustedHTML createHTMLNoArgs(
String input,
);
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/dom_window_extension.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/dom_window_extension.dart",
"repo_id": "packages",
"token_count": 459
} | 1,078 |
// 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:google_maps/google_maps.dart' as gmaps;
import '../../google_maps_flutter_web.dart';
/// A void function that handles a [gmaps.LatLng] as a parameter.
///
/// Similar to [ui.VoidCallback], but specific for Marker drag events.
typedef LatLngCallback = void Function(gmaps.LatLng latLng);
/// The base class for all "geometry" group controllers.
///
/// This lets all Geometry controllers ([MarkersController], [CirclesController],
/// [PolygonsController], [PolylinesController]) to be bound to a [gmaps.GMap]
/// instance and our internal `mapId` value.
abstract class GeometryController {
/// The GMap instance that this controller operates on.
late gmaps.GMap googleMap;
/// The map ID for events.
late int mapId;
/// Binds a `mapId` and the [gmaps.GMap] instance to this controller.
void bindToMap(int mapId, gmaps.GMap googleMap) {
this.mapId = mapId;
this.googleMap = googleMap;
}
}
| packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/types.dart/0 | {
"file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/lib/src/types.dart",
"repo_id": "packages",
"token_count": 338
} | 1,079 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.flutter.plugins.googlesigninexample">
<!-- Flutter needs internet permission to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:usesCleartextTraffic="true">
<activity
android:name=".GoogleSignInTestActivity"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
</activity>
</application>
</manifest>
| packages/packages/google_sign_in/google_sign_in/example/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/example/android/app/src/debug/AndroidManifest.xml",
"repo_id": "packages",
"token_count": 331
} | 1,080 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'stub.dart';
/// Renders a SIGN IN button that calls `handleSignIn` onclick.
Widget buildSignInButton({HandleSignInFn? onPressed}) {
return ElevatedButton(
onPressed: onPressed,
child: const Text('SIGN IN'),
);
}
| packages/packages/google_sign_in/google_sign_in/example/lib/src/sign_in_button/mobile.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/example/lib/src/sign_in_button/mobile.dart",
"repo_id": "packages",
"token_count": 138
} | 1,081 |
<!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>
<meta charset="UTF-8">
<meta name="google-signin-client_id" content="your-client_id.apps.googleusercontent.com">
<title>Google Sign-in Example</title>
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function(ev) {
_flutter.loader.loadEntrypoint({
onEntrypointLoaded: function(engineInitializer) {
engineInitializer.autoStart();
}
});
});
</script>
</body>
</html>
| packages/packages/google_sign_in/google_sign_in/example/web/index.html/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in/example/web/index.html",
"repo_id": "packages",
"token_count": 245
} | 1,082 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs, avoid_print
import 'dart:async';
import 'dart:convert' show json;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(
const MaterialApp(
title: 'Google Sign In',
home: SignInDemo(),
),
);
}
class SignInDemo extends StatefulWidget {
const SignInDemo({super.key});
@override
State createState() => SignInDemoState();
}
class SignInDemoState extends State<SignInDemo> {
GoogleSignInUserData? _currentUser;
String _contactText = '';
// Future that completes when `initWithParams` has completed on the sign in
// instance.
Future<void>? _initialization;
@override
void initState() {
super.initState();
_signIn();
}
Future<void> _ensureInitialized() {
return _initialization ??=
GoogleSignInPlatform.instance.initWithParams(const SignInInitParameters(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
))
..catchError((dynamic _) {
_initialization = null;
});
}
void _setUser(GoogleSignInUserData? user) {
setState(() {
_currentUser = user;
if (user != null) {
_handleGetContact(user);
}
});
}
Future<void> _signIn() async {
await _ensureInitialized();
final GoogleSignInUserData? newUser =
await GoogleSignInPlatform.instance.signInSilently();
_setUser(newUser);
}
Future<Map<String, String>> _getAuthHeaders() async {
final GoogleSignInUserData? user = _currentUser;
if (user == null) {
throw StateError('No user signed in');
}
final GoogleSignInTokenData response =
await GoogleSignInPlatform.instance.getTokens(
email: user.email,
shouldRecoverAuth: true,
);
return <String, String>{
'Authorization': 'Bearer ${response.accessToken}',
// TODO(kevmoo): Use the correct value once it's available.
// See https://github.com/flutter/flutter/issues/80905
'X-Goog-AuthUser': '0',
};
}
Future<void> _handleGetContact(GoogleSignInUserData user) async {
setState(() {
_contactText = 'Loading contact info...';
});
final http.Response response = await http.get(
Uri.parse('https://people.googleapis.com/v1/people/me/connections'
'?requestMask.includeField=person.names'),
headers: await _getAuthHeaders(),
);
if (response.statusCode != 200) {
setState(() {
_contactText = 'People API gave a ${response.statusCode} '
'response. Check logs for details.';
});
print('People API ${response.statusCode} response: ${response.body}');
return;
}
final Map<String, dynamic> data =
json.decode(response.body) as Map<String, dynamic>;
final int contactCount =
(data['connections'] as List<dynamic>?)?.length ?? 0;
setState(() {
_contactText = '$contactCount contacts found';
});
}
Future<void> _handleSignIn() async {
try {
await _ensureInitialized();
_setUser(await GoogleSignInPlatform.instance.signIn());
} catch (error) {
final bool canceled =
error is PlatformException && error.code == 'sign_in_canceled';
if (!canceled) {
print(error);
}
}
}
Future<void> _handleSignOut() async {
await _ensureInitialized();
await GoogleSignInPlatform.instance.disconnect();
}
Widget _buildBody() {
final GoogleSignInUserData? user = _currentUser;
if (user != null) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ListTile(
title: Text(user.displayName ?? ''),
subtitle: Text(user.email),
),
const Text('Signed in successfully.'),
Text(_contactText),
ElevatedButton(
onPressed: _handleSignOut,
child: const Text('SIGN OUT'),
),
ElevatedButton(
child: const Text('REFRESH'),
onPressed: () => _handleGetContact(user),
),
],
);
} else {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
const Text('You are not currently signed in.'),
ElevatedButton(
onPressed: _handleSignIn,
child: const Text('SIGN IN'),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Sign In'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}
| packages/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_ios/example/lib/main.dart",
"repo_id": "packages",
"token_count": 2073
} | 1,083 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:google_sign_in_web/google_sign_in_web.dart';
import 'src/button_configuration_column.dart';
// The instance of the plugin is automatically created by Flutter before calling
// our main code, let's grab it directly from the Platform interface of the plugin.
final GoogleSignInPlugin _plugin =
GoogleSignInPlatform.instance as GoogleSignInPlugin;
Future<void> main() async {
await _plugin.initWithParams(const SignInInitParameters(
clientId: 'your-client_id.apps.googleusercontent.com',
));
runApp(
const MaterialApp(
title: 'Sign in with Google button Tester',
home: ButtonConfiguratorDemo(),
),
);
}
/// The home widget of this app.
class ButtonConfiguratorDemo extends StatefulWidget {
/// A const constructor for the Widget.
const ButtonConfiguratorDemo({super.key});
@override
State createState() => _ButtonConfiguratorState();
}
class _ButtonConfiguratorState extends State<ButtonConfiguratorDemo> {
GoogleSignInUserData? _userData; // sign-in information?
GSIButtonConfiguration? _buttonConfiguration; // button configuration
@override
void initState() {
super.initState();
_plugin.userDataEvents?.listen((GoogleSignInUserData? userData) {
setState(() {
_userData = userData;
});
});
}
void _handleSignOut() {
_plugin.signOut();
setState(() {
// signOut does not broadcast through the userDataEvents, so we fake it.
_userData = null;
});
}
void _handleNewWebButtonConfiguration(GSIButtonConfiguration newConfig) {
setState(() {
_buttonConfiguration = newConfig;
});
}
Widget _buildBody() {
return Row(
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_userData == null)
_plugin.renderButton(configuration: _buttonConfiguration),
if (_userData != null) ...<Widget>[
Text('Hello, ${_userData!.displayName}!'),
ElevatedButton(
onPressed: _handleSignOut,
child: const Text('SIGN OUT'),
),
]
],
),
),
renderWebButtonConfiguration(
_buttonConfiguration,
onChange: _userData == null ? _handleNewWebButtonConfiguration : null,
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sign in with Google button Tester'),
),
body: ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: _buildBody(),
));
}
}
| packages/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart/0 | {
"file_path": "packages/packages/google_sign_in/google_sign_in_web/example/lib/button_tester.dart",
"repo_id": "packages",
"token_count": 1170
} | 1,084 |
<?code-excerpt path-base="example/lib"?>
# image\_picker\_android
The Android implementation of [`image_picker`][1].
## Usage
This package is [endorsed][2], which means you can simply use `image_picker`
normally. This package will be automatically included in your app when you do,
so you do not need to add it to your `pubspec.yaml`.
However, if you `import` this package to use any of its APIs directly, you
should add it to your `pubspec.yaml` as usual.
## Photo Picker
This package has optional Android Photo Picker functionality.
To use this feature, add the following code to your app before calling any `image_picker` APIs:
<?code-excerpt "main.dart (photo-picker-example)"?>
```dart
import 'package:image_picker_android/image_picker_android.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
// Β·Β·Β·
final ImagePickerPlatform imagePickerImplementation =
ImagePickerPlatform.instance;
if (imagePickerImplementation is ImagePickerAndroid) {
imagePickerImplementation.useAndroidPhotoPicker = true;
}
```
[1]: https://pub.dev/packages/image_picker
[2]: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#endorsed-federated-plugin
| packages/packages/image_picker/image_picker_android/README.md/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/README.md",
"repo_id": "packages",
"token_count": 381
} | 1,085 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.imagepicker;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import androidx.exifinterface.media.ExifInterface;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ExifDataCopierTest {
@Mock ExifInterface mockOldExif;
@Mock ExifInterface mockNewExif;
ExifDataCopier exifDataCopier = new ExifDataCopier();
AutoCloseable mockCloseable;
String orientationValue = "Horizontal (normal)";
String imageWidthValue = "4032";
String whitePointValue = "0.96419 1 0.82489";
String colorSpaceValue = "Uncalibrated";
String exposureTimeValue = "1/9";
String exposureModeValue = "Auto";
String exifVersionValue = "0232";
String makeValue = "Apple";
String dateTimeOriginalValue = "2023:02:14 18:55:19";
String offsetTimeValue = "+01:00";
@Before
public void setUp() {
mockCloseable = MockitoAnnotations.openMocks(this);
}
@After
public void tearDown() throws Exception {
mockCloseable.close();
}
@Test
public void copyExif_copiesOrientationAttribute() throws IOException {
when(mockOldExif.getAttribute(ExifInterface.TAG_ORIENTATION)).thenReturn(orientationValue);
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif).setAttribute(ExifInterface.TAG_ORIENTATION, orientationValue);
}
@Test
public void copyExif_doesNotCopyCategory1AttributesExceptForOrientation() throws IOException {
when(mockOldExif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH)).thenReturn(imageWidthValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_WHITE_POINT)).thenReturn(whitePointValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_COLOR_SPACE)).thenReturn(colorSpaceValue);
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif, never()).setAttribute(eq(ExifInterface.TAG_IMAGE_WIDTH), any());
verify(mockNewExif, never()).setAttribute(eq(ExifInterface.TAG_WHITE_POINT), any());
verify(mockNewExif, never()).setAttribute(eq(ExifInterface.TAG_COLOR_SPACE), any());
}
@Test
public void copyExif_copiesCategory2Attributes() throws IOException {
when(mockOldExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)).thenReturn(exposureTimeValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_EXPOSURE_MODE)).thenReturn(exposureModeValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_EXIF_VERSION)).thenReturn(exifVersionValue);
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif).setAttribute(ExifInterface.TAG_EXPOSURE_TIME, exposureTimeValue);
verify(mockNewExif).setAttribute(ExifInterface.TAG_EXPOSURE_MODE, exposureModeValue);
verify(mockNewExif).setAttribute(ExifInterface.TAG_EXIF_VERSION, exifVersionValue);
}
@Test
public void copyExif_copiesCategory3Attributes() throws IOException {
when(mockOldExif.getAttribute(ExifInterface.TAG_MAKE)).thenReturn(makeValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL))
.thenReturn(dateTimeOriginalValue);
when(mockOldExif.getAttribute(ExifInterface.TAG_OFFSET_TIME)).thenReturn(offsetTimeValue);
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif).setAttribute(ExifInterface.TAG_MAKE, makeValue);
verify(mockNewExif).setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateTimeOriginalValue);
verify(mockNewExif).setAttribute(ExifInterface.TAG_OFFSET_TIME, offsetTimeValue);
}
@Test
public void copyExif_doesNotCopyUnsetAttributes() throws IOException {
when(mockOldExif.getAttribute(ExifInterface.TAG_EXPOSURE_TIME)).thenReturn(null);
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif, never()).setAttribute(eq(ExifInterface.TAG_EXPOSURE_TIME), any());
}
@Test
public void copyExif_savesAttributes() throws IOException {
exifDataCopier.copyExif(mockOldExif, mockNewExif);
verify(mockNewExif).saveAttributes();
}
}
| packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ExifDataCopierTest.java/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ExifDataCopierTest.java",
"repo_id": "packages",
"token_count": 1523
} | 1,086 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| packages/packages/image_picker/image_picker_android/example/android/gradle.properties/0 | {
"file_path": "packages/packages/image_picker/image_picker_android/example/android/gradle.properties",
"repo_id": "packages",
"token_count": 30
} | 1,087 |
// 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 <XCTest/XCTest.h>
#import <os/log.h>
const int kElementWaitingTime = 30;
@interface ImagePickerFromGalleryUITests : XCTestCase
@property(nonatomic, strong) XCUIApplication *app;
@property(nonatomic, assign) BOOL interceptedPermissionInterruption;
@end
@implementation ImagePickerFromGalleryUITests
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
self.app = [[XCUIApplication alloc] init];
if (@available(iOS 13.4, *)) {
// Reset the authorization status for Photos to test permission popups
[self.app resetAuthorizationStatusForResource:XCUIProtectedResourcePhotos];
}
[self.app launch];
self.interceptedPermissionInterruption = NO;
__weak typeof(self) weakSelf = self;
[self addUIInterruptionMonitorWithDescription:@"Permission popups"
handler:^BOOL(XCUIElement *_Nonnull interruptingElement) {
if (@available(iOS 14, *)) {
XCUIElement *allPhotoPermission =
interruptingElement
.buttons[weakSelf.allowAccessPermissionText];
if (![allPhotoPermission waitForExistenceWithTimeout:
kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@",
weakSelf.app.debugDescription);
XCTFail(@"Failed due to not able to find "
@"allPhotoPermission button with %@ seconds",
@(kElementWaitingTime));
}
[allPhotoPermission tap];
} else {
XCUIElement *ok = interruptingElement.buttons[@"OK"];
if (![ok waitForExistenceWithTimeout:
kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@",
weakSelf.app.debugDescription);
XCTFail(@"Failed due to not able to find ok button "
@"with %@ seconds",
@(kElementWaitingTime));
}
[ok tap];
}
weakSelf.interceptedPermissionInterruption = YES;
return YES;
}];
}
- (void)tearDown {
[super tearDown];
[self.app terminate];
}
- (NSString *)allowAccessPermissionText {
NSString *fullAccessButtonText = @"Allow Access to All Photos";
if (@available(iOS 17, *)) {
fullAccessButtonText = @"Allow Full Access";
}
return fullAccessButtonText;
}
- (void)handlePermissionInterruption {
// addUIInterruptionMonitorWithDescription is only invoked when trying to interact with an element
// (the app in this case) the alert is blocking. We expect a permission popup here so do a swipe
// up action (which should be harmless).
[self.app swipeUp];
if (@available(iOS 17, *)) {
// addUIInterruptionMonitorWithDescription does not work consistently on Xcode 15 simulators, so
// use a backup method of accepting permissions popup.
if (self.interceptedPermissionInterruption == YES) {
return;
}
// If cancel button exists, permission has already been given.
XCUIElement *cancelButton = self.app.buttons[@"Cancel"].firstMatch;
if ([cancelButton waitForExistenceWithTimeout:kElementWaitingTime]) {
return;
}
XCUIApplication *springboardApp =
[[XCUIApplication alloc] initWithBundleIdentifier:@"com.apple.springboard"];
XCUIElement *allowButton = springboardApp.buttons[self.allowAccessPermissionText];
if (![allowButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find Allow Access button with %@ seconds",
@(kElementWaitingTime));
}
[allowButton tap];
}
}
- (void)testCancel {
// Find and tap on the pick from gallery button.
XCUIElement *imageFromGalleryButton =
self.app.otherElements[@"image_picker_example_from_gallery"].firstMatch;
if (![imageFromGalleryButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find image from gallery button with %@ seconds",
@(kElementWaitingTime));
}
[imageFromGalleryButton tap];
// Find and tap on the `pick` button.
XCUIElement *pickButton = self.app.buttons[@"PICK"].firstMatch;
if (![pickButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find pick button with %@ seconds", @(kElementWaitingTime));
}
[pickButton tap];
[self handlePermissionInterruption];
// Find and tap on the `Cancel` button.
XCUIElement *cancelButton = self.app.buttons[@"Cancel"].firstMatch;
if (![cancelButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find Cancel button with %@ seconds",
@(kElementWaitingTime));
}
[cancelButton tap];
// Find the "not picked image text".
XCUIElement *imageNotPickedText =
self.app.staticTexts[@"You have not yet picked an image."].firstMatch;
if (![imageNotPickedText waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find imageNotPickedText with %@ seconds",
@(kElementWaitingTime));
}
}
- (void)testPickingFromGallery {
[self launchPickerAndPickWithMaxWidth:nil maxHeight:nil quality:nil];
}
- (void)testPickingWithContraintsFromGallery {
[self launchPickerAndPickWithMaxWidth:@200 maxHeight:@100 quality:@50];
}
- (void)launchPickerAndPickWithMaxWidth:(NSNumber *)maxWidth
maxHeight:(NSNumber *)maxHeight
quality:(NSNumber *)quality {
// Find and tap on the pick from gallery button.
XCUIElement *imageFromGalleryButton =
self.app.otherElements[@"image_picker_example_from_gallery"].firstMatch;
if (![imageFromGalleryButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find image from gallery button with %@ seconds",
@(kElementWaitingTime));
}
[imageFromGalleryButton tap];
if (maxWidth != nil) {
XCUIElement *field = self.app.textFields[@"Enter maxWidth if desired"].firstMatch;
[field tap];
[field typeText:maxWidth.stringValue];
}
if (maxHeight != nil) {
XCUIElement *field = self.app.textFields[@"Enter maxHeight if desired"].firstMatch;
[field tap];
[field typeText:maxHeight.stringValue];
}
if (quality != nil) {
XCUIElement *field = self.app.textFields[@"Enter quality if desired"].firstMatch;
[field tap];
[field typeText:quality.stringValue];
}
// Find and tap on the `pick` button.
XCUIElement *pickButton = self.app.buttons[@"PICK"].firstMatch;
if (![pickButton waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find pick button with %@ seconds", @(kElementWaitingTime));
}
[pickButton tap];
[self handlePermissionInterruption];
// Find an image and tap on it. (IOS 14 UI, images are showing directly)
XCUIElement *aImage;
if (@available(iOS 14, *)) {
aImage = [self.app.scrollViews.firstMatch.images elementBoundByIndex:1];
} else {
XCUIElement *allPhotosCell = self.app.cells[@"All Photos"].firstMatch;
if (![allPhotosCell waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find \"All Photos\" cell with %@ seconds",
@(kElementWaitingTime));
}
[allPhotosCell tap];
aImage = [self.app.collectionViews elementMatchingType:XCUIElementTypeCollectionView
identifier:@"PhotosGridView"]
.cells.firstMatch;
}
os_log_error(OS_LOG_DEFAULT, "description before picking image %@", self.app.debugDescription);
if (![aImage waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find an image with %@ seconds", @(kElementWaitingTime));
}
[aImage tap];
// Find the picked image.
XCUIElement *pickedImage = self.app.images[@"image_picker_example_picked_image"].firstMatch;
if (![pickedImage waitForExistenceWithTimeout:kElementWaitingTime]) {
os_log_error(OS_LOG_DEFAULT, "%@", self.app.debugDescription);
XCTFail(@"Failed due to not able to find pickedImage with %@ seconds", @(kElementWaitingTime));
}
}
@end
| packages/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromGalleryUITests.m/0 | {
"file_path": "packages/packages/image_picker/image_picker_ios/example/ios/RunnerUITests/ImagePickerFromGalleryUITests.m",
"repo_id": "packages",
"token_count": 4369
} | 1,088 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file_selector_macos/file_selector_macos.dart';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
/// The macOS implementation of [ImagePickerPlatform].
///
/// This class implements the `package:image_picker` functionality for
/// macOS.
class ImagePickerMacOS extends CameraDelegatingImagePickerPlatform {
/// Constructs a platform implementation.
ImagePickerMacOS();
/// The file selector used to prompt the user to select images or videos.
@visibleForTesting
static FileSelectorPlatform fileSelector = FileSelectorMacOS();
/// Registers this class as the default instance of [ImagePickerPlatform].
static void registerWith() {
ImagePickerPlatform.instance = ImagePickerMacOS();
}
// This is soft-deprecated in the platform interface, and is only implemented
// for compatibility. Callers should be using getImageFromSource.
@override
Future<PickedFile?> pickImage({
required ImageSource source,
double? maxWidth,
double? maxHeight,
int? imageQuality,
CameraDevice preferredCameraDevice = CameraDevice.rear,
}) async {
final XFile? file = await getImage(
source: source,
maxWidth: maxWidth,
maxHeight: maxHeight,
imageQuality: imageQuality,
preferredCameraDevice: preferredCameraDevice);
if (file != null) {
return PickedFile(file.path);
}
return null;
}
// This is soft-deprecated in the platform interface, and is only implemented
// for compatibility. Callers should be using getVideo.
@override
Future<PickedFile?> pickVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) async {
final XFile? file = await getVideo(
source: source,
preferredCameraDevice: preferredCameraDevice,
maxDuration: maxDuration);
if (file != null) {
return PickedFile(file.path);
}
return null;
}
// This is soft-deprecated in the platform interface, and is only implemented
// for compatibility. Callers should be using getImageFromSource.
@override
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));
}
// [ImagePickerOptions] options are not currently supported. If any
// of its fields are set, they will be silently ignored.
//
// If source is `ImageSource.camera`, a `StateError` will be thrown
// unless a [cameraDelegate] is set.
@override
Future<XFile?> getImageFromSource({
required ImageSource source,
ImagePickerOptions options = const ImagePickerOptions(),
}) async {
switch (source) {
case ImageSource.camera:
return super.getImageFromSource(source: source);
case ImageSource.gallery:
// TODO(stuartmorgan): Add a native implementation that can use
// PHPickerViewController on macOS 13+, with this as a fallback for
// older OS versions: https://github.com/flutter/flutter/issues/125829.
const XTypeGroup typeGroup =
XTypeGroup(uniformTypeIdentifiers: <String>['public.image']);
final XFile? file = await fileSelector
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
return file;
}
// Ensure that there's a fallback in case a new source is added.
// ignore: dead_code
throw UnimplementedError('Unknown ImageSource: $source');
}
// `preferredCameraDevice` and `maxDuration` arguments are not currently
// supported. If either of these arguments are supplied, they will be silently
// ignored.
//
// If source is `ImageSource.camera`, a `StateError` will be thrown
// unless a [cameraDelegate] is set.
@override
Future<XFile?> getVideo({
required ImageSource source,
CameraDevice preferredCameraDevice = CameraDevice.rear,
Duration? maxDuration,
}) async {
switch (source) {
case ImageSource.camera:
return super.getVideo(
source: source,
preferredCameraDevice: preferredCameraDevice,
maxDuration: maxDuration);
case ImageSource.gallery:
const XTypeGroup typeGroup =
XTypeGroup(uniformTypeIdentifiers: <String>['public.movie']);
final XFile? file = await fileSelector
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
return file;
}
// Ensure that there's a fallback in case a new source is added.
// ignore: dead_code
throw UnimplementedError('Unknown ImageSource: $source');
}
// `maxWidth`, `maxHeight`, and `imageQuality` arguments are not currently
// supported. If any of these arguments are supplied, they will be silently
// ignored.
@override
Future<List<XFile>> getMultiImage({
double? maxWidth,
double? maxHeight,
int? imageQuality,
}) async {
// TODO(stuartmorgan): Add a native implementation that can use
// PHPickerViewController on macOS 13+, with this as a fallback for
// older OS versions: https://github.com/flutter/flutter/issues/125829.
const XTypeGroup typeGroup =
XTypeGroup(uniformTypeIdentifiers: <String>['public.image']);
final List<XFile> files = await fileSelector
.openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
return files;
}
// `maxWidth`, `maxHeight`, and `imageQuality` arguments are not currently
// supported. If any of these arguments are supplied, they will be silently
// ignored.
@override
Future<List<XFile>> getMedia({required MediaOptions options}) async {
const XTypeGroup typeGroup = XTypeGroup(
label: 'images and videos',
extensions: <String>['public.image', 'public.movie']);
List<XFile> files;
if (options.allowMultiple) {
files = await fileSelector
.openFiles(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
} else {
final XFile? file = await fileSelector
.openFile(acceptedTypeGroups: <XTypeGroup>[typeGroup]);
files = <XFile>[
if (file != null) file,
];
}
return files;
}
}
| packages/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_macos/lib/image_picker_macos.dart",
"repo_id": "packages",
"token_count": 2262
} | 1,089 |
// 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 '../../image_picker_platform_interface.dart';
/// Specifies options for selecting items when using [ImagePickerPlatform.getMedia].
@immutable
class MediaOptions {
/// Construct a new MediaOptions instance.
const MediaOptions({
this.imageOptions = const ImageOptions(),
required this.allowMultiple,
});
/// Options that will apply to images upon selection.
final ImageOptions imageOptions;
/// Whether to allow for selecting multiple media.
final bool allowMultiple;
}
| packages/packages/image_picker/image_picker_platform_interface/lib/src/types/media_options.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/media_options.dart",
"repo_id": "packages",
"token_count": 184
} | 1,090 |
// 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('vm') // Uses dart:io
library;
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
final String pathPrefix =
Directory.current.path.endsWith('test') ? './assets/' : './test/assets/';
final String path = '${pathPrefix}hello.txt';
const String expectedStringContents = 'Hello, world!';
final Uint8List bytes = Uint8List.fromList(utf8.encode(expectedStringContents));
final File textFile = File(path);
final String textFilePath = textFile.path;
void main() {
group('Create with an objectUrl', () {
final PickedFile pickedFile = PickedFile(textFilePath);
test('Can be read as a string', () async {
expect(await pickedFile.readAsString(), equals(expectedStringContents));
});
test('Can be read as bytes', () async {
expect(await pickedFile.readAsBytes(), equals(bytes));
});
test('Can be read as a stream', () async {
expect(await pickedFile.openRead().first, equals(bytes));
});
test('Stream can be sliced', () async {
expect(
await pickedFile.openRead(2, 5).first, equals(bytes.sublist(2, 5)));
});
});
}
| packages/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart/0 | {
"file_path": "packages/packages/image_picker/image_picker_platform_interface/test/picked_file_io_test.dart",
"repo_id": "packages",
"token_count": 476
} | 1,091 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.AccountIdentifiers;
import com.android.billingclient.api.AlternativeBillingOnlyReportingDetails;
import com.android.billingclient.api.BillingConfig;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.UserChoiceDetails;
import com.android.billingclient.api.UserChoiceDetails.Product;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Currency;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Handles serialization and deserialization of {@link com.android.billingclient.api.BillingClient}
* related objects.
*/
/*package*/ class Translator {
static HashMap<String, Object> fromProductDetail(ProductDetails detail) {
HashMap<String, Object> info = new HashMap<>();
info.put("title", detail.getTitle());
info.put("description", detail.getDescription());
info.put("productId", detail.getProductId());
info.put("productType", detail.getProductType());
info.put("name", detail.getName());
@Nullable
ProductDetails.OneTimePurchaseOfferDetails oneTimePurchaseOfferDetails =
detail.getOneTimePurchaseOfferDetails();
if (oneTimePurchaseOfferDetails != null) {
info.put(
"oneTimePurchaseOfferDetails",
fromOneTimePurchaseOfferDetails(oneTimePurchaseOfferDetails));
}
@Nullable
List<ProductDetails.SubscriptionOfferDetails> subscriptionOfferDetailsList =
detail.getSubscriptionOfferDetails();
if (subscriptionOfferDetailsList != null) {
info.put(
"subscriptionOfferDetails",
fromSubscriptionOfferDetailsList(subscriptionOfferDetailsList));
}
return info;
}
static List<QueryProductDetailsParams.Product> toProductList(List<Object> serialized) {
List<QueryProductDetailsParams.Product> products = new ArrayList<>();
for (Object productSerialized : serialized) {
@SuppressWarnings(value = "unchecked")
Map<String, Object> productMap = (Map<String, Object>) productSerialized;
products.add(toProduct(productMap));
}
return products;
}
static QueryProductDetailsParams.Product toProduct(Map<String, Object> serialized) {
String productId = (String) serialized.get("productId");
String productType = (String) serialized.get("productType");
return QueryProductDetailsParams.Product.newBuilder()
.setProductId(productId)
.setProductType(productType)
.build();
}
static List<HashMap<String, Object>> fromProductDetailsList(
@Nullable List<ProductDetails> productDetailsList) {
if (productDetailsList == null) {
return Collections.emptyList();
}
ArrayList<HashMap<String, Object>> output = new ArrayList<>();
for (ProductDetails detail : productDetailsList) {
output.add(fromProductDetail(detail));
}
return output;
}
static HashMap<String, Object> fromOneTimePurchaseOfferDetails(
@Nullable ProductDetails.OneTimePurchaseOfferDetails oneTimePurchaseOfferDetails) {
HashMap<String, Object> serialized = new HashMap<>();
if (oneTimePurchaseOfferDetails == null) {
return serialized;
}
serialized.put("priceAmountMicros", oneTimePurchaseOfferDetails.getPriceAmountMicros());
serialized.put("priceCurrencyCode", oneTimePurchaseOfferDetails.getPriceCurrencyCode());
serialized.put("formattedPrice", oneTimePurchaseOfferDetails.getFormattedPrice());
return serialized;
}
static List<HashMap<String, Object>> fromSubscriptionOfferDetailsList(
@Nullable List<ProductDetails.SubscriptionOfferDetails> subscriptionOfferDetailsList) {
if (subscriptionOfferDetailsList == null) {
return Collections.emptyList();
}
ArrayList<HashMap<String, Object>> serialized = new ArrayList<>();
for (ProductDetails.SubscriptionOfferDetails subscriptionOfferDetails :
subscriptionOfferDetailsList) {
serialized.add(fromSubscriptionOfferDetails(subscriptionOfferDetails));
}
return serialized;
}
static HashMap<String, Object> fromSubscriptionOfferDetails(
@Nullable ProductDetails.SubscriptionOfferDetails subscriptionOfferDetails) {
HashMap<String, Object> serialized = new HashMap<>();
if (subscriptionOfferDetails == null) {
return serialized;
}
serialized.put("offerId", subscriptionOfferDetails.getOfferId());
serialized.put("basePlanId", subscriptionOfferDetails.getBasePlanId());
serialized.put("offerTags", subscriptionOfferDetails.getOfferTags());
serialized.put("offerIdToken", subscriptionOfferDetails.getOfferToken());
ProductDetails.PricingPhases pricingPhases = subscriptionOfferDetails.getPricingPhases();
serialized.put("pricingPhases", fromPricingPhases(pricingPhases));
return serialized;
}
static List<HashMap<String, Object>> fromPricingPhases(
@NonNull ProductDetails.PricingPhases pricingPhases) {
ArrayList<HashMap<String, Object>> serialized = new ArrayList<>();
for (ProductDetails.PricingPhase pricingPhase : pricingPhases.getPricingPhaseList()) {
serialized.add(fromPricingPhase(pricingPhase));
}
return serialized;
}
static HashMap<String, Object> fromPricingPhase(
@Nullable ProductDetails.PricingPhase pricingPhase) {
HashMap<String, Object> serialized = new HashMap<>();
if (pricingPhase == null) {
return serialized;
}
serialized.put("formattedPrice", pricingPhase.getFormattedPrice());
serialized.put("priceCurrencyCode", pricingPhase.getPriceCurrencyCode());
serialized.put("priceAmountMicros", pricingPhase.getPriceAmountMicros());
serialized.put("billingCycleCount", pricingPhase.getBillingCycleCount());
serialized.put("billingPeriod", pricingPhase.getBillingPeriod());
serialized.put("recurrenceMode", pricingPhase.getRecurrenceMode());
return serialized;
}
static HashMap<String, Object> fromPurchase(Purchase purchase) {
HashMap<String, Object> info = new HashMap<>();
List<String> products = purchase.getProducts();
info.put("orderId", purchase.getOrderId());
info.put("packageName", purchase.getPackageName());
info.put("purchaseTime", purchase.getPurchaseTime());
info.put("purchaseToken", purchase.getPurchaseToken());
info.put("signature", purchase.getSignature());
info.put("products", products);
info.put("isAutoRenewing", purchase.isAutoRenewing());
info.put("originalJson", purchase.getOriginalJson());
info.put("developerPayload", purchase.getDeveloperPayload());
info.put("isAcknowledged", purchase.isAcknowledged());
info.put("purchaseState", purchase.getPurchaseState());
info.put("quantity", purchase.getQuantity());
AccountIdentifiers accountIdentifiers = purchase.getAccountIdentifiers();
if (accountIdentifiers != null) {
info.put("obfuscatedAccountId", accountIdentifiers.getObfuscatedAccountId());
info.put("obfuscatedProfileId", accountIdentifiers.getObfuscatedProfileId());
}
return info;
}
static HashMap<String, Object> fromPurchaseHistoryRecord(
PurchaseHistoryRecord purchaseHistoryRecord) {
HashMap<String, Object> info = new HashMap<>();
List<String> products = purchaseHistoryRecord.getProducts();
info.put("purchaseTime", purchaseHistoryRecord.getPurchaseTime());
info.put("purchaseToken", purchaseHistoryRecord.getPurchaseToken());
info.put("signature", purchaseHistoryRecord.getSignature());
info.put("products", products);
info.put("developerPayload", purchaseHistoryRecord.getDeveloperPayload());
info.put("originalJson", purchaseHistoryRecord.getOriginalJson());
info.put("quantity", purchaseHistoryRecord.getQuantity());
return info;
}
static List<HashMap<String, Object>> fromPurchasesList(@Nullable List<Purchase> purchases) {
if (purchases == null) {
return Collections.emptyList();
}
List<HashMap<String, Object>> serialized = new ArrayList<>();
for (Purchase purchase : purchases) {
serialized.add(fromPurchase(purchase));
}
return serialized;
}
static List<HashMap<String, Object>> fromPurchaseHistoryRecordList(
@Nullable List<PurchaseHistoryRecord> purchaseHistoryRecords) {
if (purchaseHistoryRecords == null) {
return Collections.emptyList();
}
List<HashMap<String, Object>> serialized = new ArrayList<>();
for (PurchaseHistoryRecord purchaseHistoryRecord : purchaseHistoryRecords) {
serialized.add(fromPurchaseHistoryRecord(purchaseHistoryRecord));
}
return serialized;
}
static HashMap<String, Object> fromBillingResult(BillingResult billingResult) {
HashMap<String, Object> info = new HashMap<>();
info.put("responseCode", billingResult.getResponseCode());
info.put("debugMessage", billingResult.getDebugMessage());
return info;
}
static HashMap<String, Object> fromUserChoiceDetails(UserChoiceDetails userChoiceDetails) {
HashMap<String, Object> info = new HashMap<>();
info.put("externalTransactionToken", userChoiceDetails.getExternalTransactionToken());
info.put("originalExternalTransactionId", userChoiceDetails.getOriginalExternalTransactionId());
info.put("products", fromProductsList(userChoiceDetails.getProducts()));
return info;
}
static List<HashMap<String, Object>> fromProductsList(List<Product> productsList) {
if (productsList.isEmpty()) {
return Collections.emptyList();
}
ArrayList<HashMap<String, Object>> output = new ArrayList<>();
for (Product product : productsList) {
output.add(fromProduct(product));
}
return output;
}
static HashMap<String, Object> fromProduct(Product product) {
HashMap<String, Object> info = new HashMap<>();
info.put("id", product.getId());
info.put("offerToken", product.getOfferToken());
info.put("productType", product.getType());
return info;
}
/** Converter from {@link BillingResult} and {@link BillingConfig} to map. */
static HashMap<String, Object> fromBillingConfig(
BillingResult result, BillingConfig billingConfig) {
HashMap<String, Object> info = fromBillingResult(result);
info.put("countryCode", billingConfig.getCountryCode());
return info;
}
/**
* Converter from {@link BillingResult} and {@link AlternativeBillingOnlyReportingDetails} to map.
*/
static HashMap<String, Object> fromAlternativeBillingOnlyReportingDetails(
BillingResult result, AlternativeBillingOnlyReportingDetails details) {
HashMap<String, Object> info = fromBillingResult(result);
if (details != null) {
info.put("externalTransactionToken", details.getExternalTransactionToken());
}
return info;
}
/**
* Gets the symbol of for the given currency code for the default {@link Locale.Category#DISPLAY
* DISPLAY} locale. For example, for the US Dollar, the symbol is "$" if the default locale is the
* US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217
* currency code is returned.
*
* @param currencyCode the ISO 4217 code of the currency
* @return the symbol of this currency code for the default {@link Locale.Category#DISPLAY
* DISPLAY} locale
* @exception NullPointerException if <code>currencyCode</code> is null
* @exception IllegalArgumentException if <code>currencyCode</code> is not a supported ISO 4217
* code.
*/
static String currencySymbolFromCode(String currencyCode) {
return Currency.getInstance(currencyCode).getSymbol();
}
}
| packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/Translator.java/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/Translator.java",
"repo_id": "packages",
"token_count": 3839
} | 1,092 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'product_details_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ProductDetailsWrapper _$ProductDetailsWrapperFromJson(Map json) =>
ProductDetailsWrapper(
description: json['description'] as String? ?? '',
name: json['name'] as String? ?? '',
oneTimePurchaseOfferDetails: json['oneTimePurchaseOfferDetails'] == null
? null
: OneTimePurchaseOfferDetailsWrapper.fromJson(
Map<String, dynamic>.from(
json['oneTimePurchaseOfferDetails'] as Map)),
productId: json['productId'] as String? ?? '',
productType: json['productType'] == null
? ProductType.subs
: const ProductTypeConverter()
.fromJson(json['productType'] as String?),
subscriptionOfferDetails:
(json['subscriptionOfferDetails'] as List<dynamic>?)
?.map((e) => SubscriptionOfferDetailsWrapper.fromJson(
Map<String, dynamic>.from(e as Map)))
.toList(),
title: json['title'] as String? ?? '',
);
ProductDetailsResponseWrapper _$ProductDetailsResponseWrapperFromJson(
Map json) =>
ProductDetailsResponseWrapper(
billingResult:
BillingResultWrapper.fromJson((json['billingResult'] as Map?)?.map(
(k, e) => MapEntry(k as String, e),
)),
productDetailsList: (json['productDetailsList'] as List<dynamic>?)
?.map((e) => ProductDetailsWrapper.fromJson(
Map<String, dynamic>.from(e as Map)))
.toList() ??
[],
);
const _$RecurrenceModeEnumMap = {
RecurrenceMode.finiteRecurring: 2,
RecurrenceMode.infiniteRecurring: 1,
RecurrenceMode.nonRecurring: 3,
};
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.g.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/product_details_wrapper.g.dart",
"repo_id": "packages",
"token_count": 751
} | 1,093 |
// 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';
/// Data structure representing a UserChoiceDetails.
///
/// This wraps [`com.android.billingclient.api.UserChoiceDetails`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceDetails)
@immutable
class GooglePlayUserChoiceDetails {
/// Creates a new Google Play specific user choice billing details object with
/// the provided details.
const GooglePlayUserChoiceDetails({
required this.originalExternalTransactionId,
required this.externalTransactionToken,
required this.products,
});
/// Returns the external transaction Id of the originating subscription, if
/// the purchase is a subscription upgrade/downgrade.
final String originalExternalTransactionId;
/// Returns a token that represents the user's prospective purchase via
/// user choice alternative billing.
final String externalTransactionToken;
/// Returns a list of [GooglePlayUserChoiceDetailsProduct] to be purchased in
/// the user choice alternative billing flow.
final List<GooglePlayUserChoiceDetailsProduct> products;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is GooglePlayUserChoiceDetails &&
other.originalExternalTransactionId == originalExternalTransactionId &&
other.externalTransactionToken == externalTransactionToken &&
listEquals(other.products, products);
}
@override
int get hashCode => Object.hash(
originalExternalTransactionId,
externalTransactionToken,
products.hashCode,
);
}
/// Data structure representing a UserChoiceDetails product.
///
/// This wraps [`com.android.billingclient.api.UserChoiceDetails.Product`](https://developer.android.com/reference/com/android/billingclient/api/UserChoiceDetails.Product)
@immutable
class GooglePlayUserChoiceDetailsProduct {
/// Creates UserChoiceDetailsProduct.
const GooglePlayUserChoiceDetailsProduct(
{required this.id, required this.offerToken, required this.productType});
/// Returns the id of the product being purchased.
final String id;
/// Returns the offer token that was passed in launchBillingFlow to purchase the product.
final String offerToken;
/// Returns the [GooglePlayProductType] of the product being purchased.
final GooglePlayProductType productType;
@override
bool operator ==(Object other) {
if (identical(other, this)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is GooglePlayUserChoiceDetailsProduct &&
other.id == id &&
other.offerToken == offerToken &&
other.productType == productType;
}
@override
int get hashCode => Object.hash(
id,
offerToken,
productType,
);
}
/// This wraps [`com.android.billingclient.api.BillingClient.ProductType`](https://developer.android.com/reference/com/android/billingclient/api/BillingClient.ProductType)
enum GooglePlayProductType {
/// A Product type for Android apps in-app products.
inapp,
/// A Product type for Android apps subscriptions.
subs
}
| packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/types/google_play_user_choice_details.dart",
"repo_id": "packages",
"token_count": 989
} | 1,094 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 1.3.7
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 1.3.6
* Updates documentation reference of `finishPurchase` to `completePurchase`.
## 1.3.5
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 1.3.4
* Removes obsolete null checks on non-nullable values.
* Updates minimum Flutter version to 3.3.
* Aligns Dart and Flutter SDK constraints.
## 1.3.3
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 1.3.2
* Updates imports for `prefer_relative_imports`.
* Updates minimum Flutter version to 2.10.
* Removes unnecessary imports.
## 1.3.1
* Update to use the `verify` method introduced in plugin_platform_interface 2.1.0.
## 1.3.0
* Added new `PurchaseStatus` named `canceled` to distinguish between an error and user cancellation.
## 1.2.0
* Added `toString()` to `IAPError`
## 1.1.0
* Added `currencySymbol` in ProductDetails.
## 1.0.1
* Fixed `Restoring previous purchases` link.
## 1.0.0
* Initial open-source release.
| packages/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_platform_interface/CHANGELOG.md",
"repo_id": "packages",
"token_count": 409
} | 1,095 |
// 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.
export 'product_details.dart';
export 'product_details_response.dart';
export 'purchase_details.dart';
export 'purchase_param.dart';
export 'purchase_status.dart';
export 'purchase_verification_data.dart';
| packages/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/types.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_platform_interface/lib/src/types/types.dart",
"repo_id": "packages",
"token_count": 111
} | 1,096 |
// 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 "FIAPReceiptManager.h"
#if TARGET_OS_OSX
#import <FlutterMacOS/FlutterMacOS.h>
#else
#import <Flutter/Flutter.h>
#endif
#import "FIAObjectTranslator.h"
@interface FIAPReceiptManager ()
// Gets the receipt file data from the location of the url. Can be nil if
// there is an error. This interface is defined so it can be stubbed for testing.
- (NSData *)getReceiptData:(NSURL *)url error:(NSError **)error;
@end
@implementation FIAPReceiptManager
- (NSString *)retrieveReceiptWithError:(FlutterError **)flutterError {
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
if (!receiptURL) {
return nil;
}
NSError *receiptError;
NSData *receipt = [self getReceiptData:receiptURL error:&receiptError];
if (!receipt || receiptError) {
if (flutterError) {
NSDictionary *errorMap = [FIAObjectTranslator getMapFromNSError:receiptError];
*flutterError =
[FlutterError errorWithCode:[NSString stringWithFormat:@"%@", errorMap[@"code"]]
message:errorMap[@"domain"]
details:errorMap[@"userInfo"]];
}
return nil;
}
return [receipt base64EncodedStringWithOptions:kNilOptions];
}
- (NSData *)getReceiptData:(NSURL *)url error:(NSError **)error {
return [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:error];
}
@end
| packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPReceiptManager.m/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/FIAPReceiptManager.m",
"repo_id": "packages",
"token_count": 590
} | 1,097 |
// 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/material.dart';
import 'package:in_app_purchase_platform_interface/in_app_purchase_platform_interface.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'consumable_store.dart';
import 'example_payment_queue_delegate.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// When using the Android plugin directly it is mandatory to register
// the plugin as default instance as part of initializing the app.
InAppPurchaseStoreKitPlatform.registerPlatform();
runApp(_MyApp());
}
const String _kConsumableId = 'consumable';
const String _kUpgradeId = 'upgrade';
const String _kSilverSubscriptionId = 'subscription_silver';
const String _kGoldSubscriptionId = 'subscription_gold';
const List<String> _kProductIds = <String>[
_kConsumableId,
_kUpgradeId,
_kSilverSubscriptionId,
_kGoldSubscriptionId,
];
class _MyApp extends StatefulWidget {
@override
State<_MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<_MyApp> {
final InAppPurchaseStoreKitPlatform _iapStoreKitPlatform =
InAppPurchasePlatform.instance as InAppPurchaseStoreKitPlatform;
final InAppPurchaseStoreKitPlatformAddition _iapStoreKitPlatformAddition =
InAppPurchasePlatformAddition.instance!
as InAppPurchaseStoreKitPlatformAddition;
late StreamSubscription<List<PurchaseDetails>> _subscription;
List<String> _notFoundIds = <String>[];
List<ProductDetails> _products = <ProductDetails>[];
List<PurchaseDetails> _purchases = <PurchaseDetails>[];
List<String> _consumables = <String>[];
bool _isAvailable = false;
bool _purchasePending = false;
bool _loading = true;
String? _queryProductError;
@override
void initState() {
final Stream<List<PurchaseDetails>> purchaseUpdated =
_iapStoreKitPlatform.purchaseStream;
_subscription =
purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
_listenToPurchaseUpdated(purchaseDetailsList);
}, onDone: () {
_subscription.cancel();
}, onError: (Object error) {
// handle error here.
});
// Register the example payment queue delegate
_iapStoreKitPlatformAddition.setDelegate(ExamplePaymentQueueDelegate());
initStoreInfo();
super.initState();
}
Future<void> initStoreInfo() async {
final bool isAvailable = await _iapStoreKitPlatform.isAvailable();
if (!isAvailable) {
setState(() {
_isAvailable = isAvailable;
_products = <ProductDetails>[];
_purchases = <PurchaseDetails>[];
_notFoundIds = <String>[];
_consumables = <String>[];
_purchasePending = false;
_loading = false;
});
return;
}
final ProductDetailsResponse productDetailResponse =
await _iapStoreKitPlatform.queryProductDetails(_kProductIds.toSet());
if (productDetailResponse.error != null) {
setState(() {
_queryProductError = productDetailResponse.error!.message;
_isAvailable = isAvailable;
_products = productDetailResponse.productDetails;
_purchases = <PurchaseDetails>[];
_notFoundIds = productDetailResponse.notFoundIDs;
_consumables = <String>[];
_purchasePending = false;
_loading = false;
});
return;
}
if (productDetailResponse.productDetails.isEmpty) {
setState(() {
_queryProductError = null;
_isAvailable = isAvailable;
_products = productDetailResponse.productDetails;
_purchases = <PurchaseDetails>[];
_notFoundIds = productDetailResponse.notFoundIDs;
_consumables = <String>[];
_purchasePending = false;
_loading = false;
});
return;
}
final List<String> consumables = await ConsumableStore.load();
setState(() {
_isAvailable = isAvailable;
_products = productDetailResponse.productDetails;
_notFoundIds = productDetailResponse.notFoundIDs;
_consumables = consumables;
_purchasePending = false;
_loading = false;
});
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final List<Widget> stack = <Widget>[];
if (_queryProductError == null) {
stack.add(
ListView(
children: <Widget>[
_buildConnectionCheckTile(),
_buildProductList(),
_buildConsumableBox(),
_buildRestoreButton(),
],
),
);
} else {
stack.add(Center(
child: Text(_queryProductError!),
));
}
if (_purchasePending) {
stack.add(
const Stack(
children: <Widget>[
Opacity(
opacity: 0.3,
child: ModalBarrier(dismissible: false, color: Colors.grey),
),
Center(
child: CircularProgressIndicator(),
),
],
),
);
}
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('IAP Example'),
),
body: Stack(
children: stack,
),
),
);
}
Card _buildConnectionCheckTile() {
if (_loading) {
return const Card(child: ListTile(title: Text('Trying to connect...')));
}
final Widget storeHeader = ListTile(
leading: Icon(_isAvailable ? Icons.check : Icons.block,
color: _isAvailable
? Colors.green
: ThemeData.light().colorScheme.error),
title:
Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'),
);
final List<Widget> children = <Widget>[storeHeader];
if (!_isAvailable) {
children.addAll(<Widget>[
const Divider(),
ListTile(
title: Text('Not connected',
style: TextStyle(color: ThemeData.light().colorScheme.error)),
subtitle: const Text(
'Unable to connect to the payments processor. Has this app been configured correctly? See the example README for instructions.'),
),
]);
}
return Card(child: Column(children: children));
}
Card _buildProductList() {
if (_loading) {
return const Card(
child: ListTile(
leading: CircularProgressIndicator(),
title: Text('Fetching products...')));
}
if (!_isAvailable) {
return const Card();
}
const ListTile productHeader = ListTile(title: Text('Products for Sale'));
final List<ListTile> productList = <ListTile>[];
if (_notFoundIds.isNotEmpty) {
productList.add(ListTile(
title: Text('[${_notFoundIds.join(", ")}] not found',
style: TextStyle(color: ThemeData.light().colorScheme.error)),
subtitle: const Text(
'This app needs special configuration to run. Please see example/README.md for instructions.')));
}
// This loading previous purchases code is just a demo. Please do not use this as it is.
// In your app you should always verify the purchase data using the `verificationData` inside the [PurchaseDetails] object before trusting it.
// We recommend that you use your own server to verify the purchase data.
final Map<String, PurchaseDetails> purchases =
Map<String, PurchaseDetails>.fromEntries(
_purchases.map((PurchaseDetails purchase) {
if (purchase.pendingCompletePurchase) {
_iapStoreKitPlatform.completePurchase(purchase);
}
return MapEntry<String, PurchaseDetails>(purchase.productID, purchase);
}));
productList.addAll(_products.map(
(ProductDetails productDetails) {
final PurchaseDetails? previousPurchase = purchases[productDetails.id];
return ListTile(
title: Text(
productDetails.title,
),
subtitle: Text(
productDetails.description,
),
trailing: previousPurchase != null
? IconButton(
onPressed: () {
_iapStoreKitPlatformAddition.showPriceConsentIfNeeded();
},
icon: const Icon(Icons.upgrade))
: TextButton(
style: TextButton.styleFrom(
backgroundColor: Colors.green[800],
foregroundColor: Colors.white,
),
onPressed: () {
final PurchaseParam purchaseParam = PurchaseParam(
productDetails: productDetails,
);
if (productDetails.id == _kConsumableId) {
_iapStoreKitPlatform.buyConsumable(
purchaseParam: purchaseParam);
} else {
_iapStoreKitPlatform.buyNonConsumable(
purchaseParam: purchaseParam);
}
},
child: Text(productDetails.price),
));
},
));
return Card(
child: Column(
children: <Widget>[productHeader, const Divider()] + productList));
}
Card _buildConsumableBox() {
if (_loading) {
return const Card(
child: ListTile(
leading: CircularProgressIndicator(),
title: Text('Fetching consumables...')));
}
if (!_isAvailable || _notFoundIds.contains(_kConsumableId)) {
return const Card();
}
const ListTile consumableHeader =
ListTile(title: Text('Purchased consumables'));
final List<Widget> tokens = _consumables.map((String id) {
return GridTile(
child: IconButton(
icon: const Icon(
Icons.stars,
size: 42.0,
color: Colors.orange,
),
splashColor: Colors.yellowAccent,
onPressed: () => consume(id),
),
);
}).toList();
return Card(
child: Column(children: <Widget>[
consumableHeader,
const Divider(),
GridView.count(
crossAxisCount: 5,
shrinkWrap: true,
padding: const EdgeInsets.all(16.0),
children: tokens,
)
]));
}
Widget _buildRestoreButton() {
if (_loading) {
return Container();
}
return Padding(
padding: const EdgeInsets.all(4.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TextButton(
style: TextButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
),
onPressed: () => _iapStoreKitPlatform.restorePurchases(),
child: const Text('Restore purchases'),
),
],
),
);
}
Future<void> consume(String id) async {
await ConsumableStore.consume(id);
final List<String> consumables = await ConsumableStore.load();
setState(() {
_consumables = consumables;
});
}
void showPendingUI() {
setState(() {
_purchasePending = true;
});
}
Future<void> deliverProduct(PurchaseDetails purchaseDetails) async {
// IMPORTANT!! Always verify purchase details before delivering the product.
if (purchaseDetails.productID == _kConsumableId) {
await ConsumableStore.save(purchaseDetails.purchaseID!);
final List<String> consumables = await ConsumableStore.load();
setState(() {
_purchasePending = false;
_consumables = consumables;
});
} else {
setState(() {
_purchases.add(purchaseDetails);
_purchasePending = false;
});
}
}
void handleError(IAPError error) {
setState(() {
_purchasePending = false;
});
}
Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) {
// IMPORTANT!! Always verify a purchase before delivering the product.
// For the purpose of an example, we directly return true.
return Future<bool>.value(true);
}
void _handleInvalidPurchase(PurchaseDetails purchaseDetails) {
// handle invalid purchase here if _verifyPurchase` failed.
}
void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
purchaseDetailsList.forEach(_handleReportedPurchaseState);
}
Future<void> _handleReportedPurchaseState(
PurchaseDetails purchaseDetails) async {
if (purchaseDetails.status == PurchaseStatus.pending) {
showPendingUI();
} else {
if (purchaseDetails.status == PurchaseStatus.error) {
handleError(purchaseDetails.error!);
} else if (purchaseDetails.status == PurchaseStatus.purchased ||
purchaseDetails.status == PurchaseStatus.restored) {
final bool valid = await _verifyPurchase(purchaseDetails);
if (valid) {
await deliverProduct(purchaseDetails);
} else {
_handleInvalidPurchase(purchaseDetails);
return;
}
}
if (purchaseDetails.pendingCompletePurchase) {
await _iapStoreKitPlatform.completePurchase(purchaseDetails);
}
}
}
}
| packages/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/lib/main.dart",
"repo_id": "packages",
"token_count": 5552
} | 1,098 |
// 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 <OCMock/OCMock.h>
#import <XCTest/XCTest.h>
#import "Stubs.h"
@import in_app_purchase_storekit;
@interface PaymentQueueTest : XCTestCase
@property(strong, nonatomic) NSDictionary *periodMap;
@property(strong, nonatomic) NSDictionary *discountMap;
@property(strong, nonatomic) NSDictionary *productMap;
@property(strong, nonatomic) NSDictionary *productResponseMap;
@end
@implementation PaymentQueueTest
- (void)setUp {
self.periodMap = @{@"numberOfUnits" : @(0), @"unit" : @(0)};
self.discountMap = @{
@"price" : @1.0,
@"currencyCode" : @"USD",
@"numberOfPeriods" : @1,
@"subscriptionPeriod" : self.periodMap,
@"paymentMode" : @1
};
self.productMap = @{
@"price" : @1.0,
@"currencyCode" : @"USD",
@"productIdentifier" : @"123",
@"localizedTitle" : @"title",
@"localizedDescription" : @"des",
@"subscriptionPeriod" : self.periodMap,
@"introductoryPrice" : self.discountMap,
@"subscriptionGroupIdentifier" : @"com.group"
};
self.productResponseMap =
@{@"products" : @[ self.productMap ], @"invalidProductIdentifiers" : [NSNull null]};
}
- (void)testTransactionPurchased {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect to get purchased transcation."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStatePurchased;
__block SKPaymentTransactionStub *tran;
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
SKPaymentTransaction *transaction = transactions[0];
tran = (SKPaymentTransactionStub *)transaction;
[expectation fulfill];
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(tran.transactionState, SKPaymentTransactionStatePurchased);
XCTAssertEqual(tran.transactionIdentifier, @"fakeID");
}
- (void)testTransactionFailed {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect to get failed transcation."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStateFailed;
__block SKPaymentTransactionStub *tran;
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
SKPaymentTransaction *transaction = transactions[0];
tran = (SKPaymentTransactionStub *)transaction;
[expectation fulfill];
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(tran.transactionState, SKPaymentTransactionStateFailed);
XCTAssertEqual(tran.transactionIdentifier, nil);
}
- (void)testTransactionRestored {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect to get restored transcation."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStateRestored;
__block SKPaymentTransactionStub *tran;
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
SKPaymentTransaction *transaction = transactions[0];
tran = (SKPaymentTransactionStub *)transaction;
[expectation fulfill];
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(tran.transactionState, SKPaymentTransactionStateRestored);
XCTAssertEqual(tran.transactionIdentifier, @"fakeID");
}
- (void)testTransactionPurchasing {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect to get purchasing transcation."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStatePurchasing;
__block SKPaymentTransactionStub *tran;
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
SKPaymentTransaction *transaction = transactions[0];
tran = (SKPaymentTransactionStub *)transaction;
[expectation fulfill];
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(tran.transactionState, SKPaymentTransactionStatePurchasing);
XCTAssertEqual(tran.transactionIdentifier, nil);
}
- (void)testTransactionDeferred {
XCTestExpectation *expectation =
[self expectationWithDescription:@"expect to get deffered transcation."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStateDeferred;
__block SKPaymentTransactionStub *tran;
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
SKPaymentTransaction *transaction = transactions[0];
tran = (SKPaymentTransactionStub *)transaction;
[expectation fulfill];
}
transactionRemoved:nil
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
XCTAssertEqual(tran.transactionState, SKPaymentTransactionStateDeferred);
XCTAssertEqual(tran.transactionIdentifier, nil);
}
- (void)testFinishTransaction {
XCTestExpectation *expectation =
[self expectationWithDescription:@"handler.transactions should be empty."];
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStateDeferred;
__block FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqual(transactions.count, 1);
SKPaymentTransaction *transaction = transactions[0];
[handler finishTransaction:transaction];
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqual(transactions.count, 1);
[expectation fulfill];
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:nil
transactionCache:OCMClassMock(FIATransactionCache.class)];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler startObservingPaymentQueue];
[handler addPayment:payment];
[self waitForExpectations:@[ expectation ] timeout:5];
}
- (void)testStartObservingPaymentQueueShouldNotProcessTransactionsWhenCacheIsEmpty {
FIATransactionCache *mockCache = OCMClassMock(FIATransactionCache.class);
FIAPaymentQueueHandler *handler =
[[FIAPaymentQueueHandler alloc] initWithQueue:[[SKPaymentQueueStub alloc] init]
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionsUpdated callback should not be called when cache is empty.");
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionRemoved callback should not be called when cache is empty.");
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:^(NSArray<SKDownload *> *_Nonnull downloads) {
XCTFail("updatedDownloads callback should not be called when cache is empty.");
}
transactionCache:mockCache];
[handler startObservingPaymentQueue];
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyRemovedTransactions]);
}
- (void)
testStartObservingPaymentQueueShouldNotProcessTransactionsWhenCacheContainsEmptyTransactionArrays {
FIATransactionCache *mockCache = OCMClassMock(FIATransactionCache.class);
FIAPaymentQueueHandler *handler =
[[FIAPaymentQueueHandler alloc] initWithQueue:[[SKPaymentQueueStub alloc] init]
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionsUpdated callback should not be called when cache is empty.");
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionRemoved callback should not be called when cache is empty.");
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:^(NSArray<SKDownload *> *_Nonnull downloads) {
XCTFail("updatedDownloads callback should not be called when cache is empty.");
}
transactionCache:mockCache];
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]).andReturn(@[]);
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]).andReturn(@[]);
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyRemovedTransactions]).andReturn(@[]);
[handler startObservingPaymentQueue];
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyRemovedTransactions]);
}
- (void)testStartObservingPaymentQueueShouldProcessTransactionsForItemsInCache {
XCTestExpectation *updateTransactionsExpectation =
[self expectationWithDescription:
@"transactionsUpdated callback should be called with one transaction."];
XCTestExpectation *removeTransactionsExpectation =
[self expectationWithDescription:
@"transactionsRemoved callback should be called with one transaction."];
XCTestExpectation *updateDownloadsExpectation =
[self expectationWithDescription:
@"downloadsUpdated callback should be called with one transaction."];
SKPaymentTransaction *mockTransaction = OCMClassMock(SKPaymentTransaction.class);
SKDownload *mockDownload = OCMClassMock(SKDownload.class);
FIATransactionCache *mockCache = OCMClassMock(FIATransactionCache.class);
FIAPaymentQueueHandler *handler =
[[FIAPaymentQueueHandler alloc] initWithQueue:[[SKPaymentQueueStub alloc] init]
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqualObjects(transactions, @[ mockTransaction ]);
[updateTransactionsExpectation fulfill];
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqualObjects(transactions, @[ mockTransaction ]);
[removeTransactionsExpectation fulfill];
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:^(NSArray<SKDownload *> *_Nonnull downloads) {
XCTAssertEqualObjects(downloads, @[ mockDownload ]);
[updateDownloadsExpectation fulfill];
}
transactionCache:mockCache];
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]).andReturn(@[
mockTransaction
]);
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]).andReturn(@[
mockDownload
]);
OCMStub([mockCache getObjectsForKey:TransactionCacheKeyRemovedTransactions]).andReturn(@[
mockTransaction
]);
[handler startObservingPaymentQueue];
[self waitForExpectations:@[
updateTransactionsExpectation, removeTransactionsExpectation, updateDownloadsExpectation
]
timeout:5];
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedTransactions]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyUpdatedDownloads]);
OCMVerify(times(1), [mockCache getObjectsForKey:TransactionCacheKeyRemovedTransactions]);
OCMVerify(times(1), [mockCache clear]);
}
- (void)testTransactionsShouldBeCachedWhenNotObserving {
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
FIATransactionCache *mockCache = OCMClassMock(FIATransactionCache.class);
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionsUpdated callback should not be called when cache is empty.");
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTFail("transactionRemoved callback should not be called when cache is empty.");
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:^(NSArray<SKDownload *> *_Nonnull downloads) {
XCTFail("updatedDownloads callback should not be called when cache is empty.");
}
transactionCache:mockCache];
SKPayment *payment =
[SKPayment paymentWithProduct:[[SKProductStub alloc] initWithMap:self.productResponseMap]];
[handler addPayment:payment];
OCMVerify(times(1), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyUpdatedTransactions]);
OCMVerify(never(), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyUpdatedDownloads]);
OCMVerify(never(), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyRemovedTransactions]);
}
- (void)testTransactionsShouldNotBeCachedWhenObserving {
XCTestExpectation *updateTransactionsExpectation =
[self expectationWithDescription:
@"transactionsUpdated callback should be called with one transaction."];
XCTestExpectation *removeTransactionsExpectation =
[self expectationWithDescription:
@"transactionsRemoved callback should be called with one transaction."];
XCTestExpectation *updateDownloadsExpectation =
[self expectationWithDescription:
@"downloadsUpdated callback should be called with one transaction."];
SKPaymentTransaction *mockTransaction = OCMClassMock(SKPaymentTransaction.class);
SKDownload *mockDownload = OCMClassMock(SKDownload.class);
SKPaymentQueueStub *queue = [[SKPaymentQueueStub alloc] init];
queue.testState = SKPaymentTransactionStatePurchased;
FIATransactionCache *mockCache = OCMClassMock(FIATransactionCache.class);
FIAPaymentQueueHandler *handler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue
transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqualObjects(transactions, @[ mockTransaction ]);
[updateTransactionsExpectation fulfill];
}
transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) {
XCTAssertEqualObjects(transactions, @[ mockTransaction ]);
[removeTransactionsExpectation fulfill];
}
restoreTransactionFailed:nil
restoreCompletedTransactionsFinished:nil
shouldAddStorePayment:^BOOL(SKPayment *_Nonnull payment, SKProduct *_Nonnull product) {
return YES;
}
updatedDownloads:^(NSArray<SKDownload *> *_Nonnull downloads) {
XCTAssertEqualObjects(downloads, @[ mockDownload ]);
[updateDownloadsExpectation fulfill];
}
transactionCache:mockCache];
[handler startObservingPaymentQueue];
[handler paymentQueue:queue updatedTransactions:@[ mockTransaction ]];
[handler paymentQueue:queue removedTransactions:@[ mockTransaction ]];
[handler paymentQueue:queue updatedDownloads:@[ mockDownload ]];
[self waitForExpectations:@[
updateTransactionsExpectation, removeTransactionsExpectation, updateDownloadsExpectation
]
timeout:5];
OCMVerify(never(), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyUpdatedTransactions]);
OCMVerify(never(), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyUpdatedDownloads]);
OCMVerify(never(), [mockCache addObjects:[OCMArg any]
forKey:TransactionCacheKeyRemovedTransactions]);
}
@end
| packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/PaymentQueueTests.m/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/PaymentQueueTests.m",
"repo_id": "packages",
"token_count": 6996
} | 1,099 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'sk_payment_queue_wrapper.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
SKError _$SKErrorFromJson(Map json) => SKError(
code: json['code'] as int? ?? 0,
domain: json['domain'] as String? ?? '',
userInfo: (json['userInfo'] as Map?)?.map(
(k, e) => MapEntry(k as String, e),
) ??
{},
);
SKPaymentWrapper _$SKPaymentWrapperFromJson(Map json) => SKPaymentWrapper(
productIdentifier: json['productIdentifier'] as String? ?? '',
applicationUsername: json['applicationUsername'] as String?,
requestData: json['requestData'] as String?,
quantity: json['quantity'] as int? ?? 0,
simulatesAskToBuyInSandbox:
json['simulatesAskToBuyInSandbox'] as bool? ?? false,
);
Map<String, dynamic> _$SKPaymentWrapperToJson(SKPaymentWrapper instance) =>
<String, dynamic>{
'productIdentifier': instance.productIdentifier,
'applicationUsername': instance.applicationUsername,
'requestData': instance.requestData,
'quantity': instance.quantity,
'simulatesAskToBuyInSandbox': instance.simulatesAskToBuyInSandbox,
};
SKPaymentDiscountWrapper _$SKPaymentDiscountWrapperFromJson(Map json) =>
SKPaymentDiscountWrapper(
identifier: json['identifier'] as String,
keyIdentifier: json['keyIdentifier'] as String,
nonce: json['nonce'] as String,
signature: json['signature'] as String,
timestamp: json['timestamp'] as int,
);
Map<String, dynamic> _$SKPaymentDiscountWrapperToJson(
SKPaymentDiscountWrapper instance) =>
<String, dynamic>{
'identifier': instance.identifier,
'keyIdentifier': instance.keyIdentifier,
'nonce': instance.nonce,
'signature': instance.signature,
'timestamp': instance.timestamp,
};
| packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_payment_queue_wrapper.g.dart",
"repo_id": "packages",
"token_count": 734
} | 1,100 |
name: in_app_purchase_storekit
description: An implementation for the iOS and macOS platforms of the Flutter `in_app_purchase` plugin. This uses the StoreKit Framework.
repository: https://github.com/flutter/packages/tree/main/packages/in_app_purchase/in_app_purchase_storekit
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
version: 0.3.13+1
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: in_app_purchase
platforms:
ios:
pluginClass: InAppPurchasePlugin
sharedDarwinSource: true
macos:
pluginClass: InAppPurchasePlugin
sharedDarwinSource: true
dependencies:
collection: ^1.15.0
flutter:
sdk: flutter
in_app_purchase_platform_interface: ^1.3.0
json_annotation: ^4.3.0
dev_dependencies:
build_runner: ^2.0.0
flutter_test:
sdk: flutter
json_serializable: ^6.0.0
pigeon: ^16.0.4
test: ^1.16.0
topics:
- in-app-purchase
- payment
| packages/packages/in_app_purchase/in_app_purchase_storekit/pubspec.yaml/0 | {
"file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/pubspec.yaml",
"repo_id": "packages",
"token_count": 424
} | 1,101 |
hello
| packages/packages/ios_platform_images/example/ios/Runner/textfile/0 | {
"file_path": "packages/packages/ios_platform_images/example/ios/Runner/textfile",
"repo_id": "packages",
"token_count": 2
} | 1,102 |
buildFlags:
_pluginToolsConfigGlobalKey:
- "--no-tree-shake-icons"
- "--dart-define=buildmode=testing"
| packages/packages/local_auth/local_auth_android/example/.pluginToolsConfig.yaml/0 | {
"file_path": "packages/packages/local_auth/local_auth_android/example/.pluginToolsConfig.yaml",
"repo_id": "packages",
"token_count": 45
} | 1,103 |
include ':app'
| packages/packages/local_auth/local_auth_android/example/android/settings_aar.gradle/0 | {
"file_path": "packages/packages/local_auth/local_auth_android/example/android/settings_aar.gradle",
"repo_id": "packages",
"token_count": 6
} | 1,104 |
// 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:intl/intl.dart';
import 'package:local_auth_platform_interface/types/auth_messages.dart';
/// Class wrapping all authentication messages needed on iOS.
/// Provides default values for all messages.
@immutable
class IOSAuthMessages extends AuthMessages {
/// Constructs a new instance.
const IOSAuthMessages({
this.lockOut,
this.goToSettingsButton,
this.goToSettingsDescription,
this.cancelButton,
this.localizedFallbackTitle,
});
/// Message advising the user to re-enable biometrics on their device.
final String? lockOut;
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
/// Maximum 30 characters.
final String? goToSettingsButton;
/// Message advising the user to go to the settings and configure Biometrics
/// for their device.
final String? goToSettingsDescription;
/// Message shown on a button that the user can click to leave the current
/// dialog.
/// Maximum 30 characters.
final String? cancelButton;
/// The localized title for the fallback button in the dialog presented to
/// the user during authentication.
final String? localizedFallbackTitle;
@override
Map<String, String> get args {
return <String, String>{
'lockOut': lockOut ?? iOSLockOut,
'goToSetting': goToSettingsButton ?? goToSettings,
'goToSettingDescriptionIOS':
goToSettingsDescription ?? iOSGoToSettingsDescription,
'okButton': cancelButton ?? iOSOkButton,
if (localizedFallbackTitle != null)
'localizedFallbackTitle': localizedFallbackTitle!,
};
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is IOSAuthMessages &&
runtimeType == other.runtimeType &&
lockOut == other.lockOut &&
goToSettingsButton == other.goToSettingsButton &&
goToSettingsDescription == other.goToSettingsDescription &&
cancelButton == other.cancelButton &&
localizedFallbackTitle == other.localizedFallbackTitle;
@override
int get hashCode => Object.hash(
super.hashCode,
lockOut,
goToSettingsButton,
goToSettingsDescription,
cancelButton,
localizedFallbackTitle,
);
}
// Default Strings for IOSAuthMessages plugin. Currently supports English.
// Intl.message must be string literals.
/// Message shown on a button that the user can click to go to settings pages
/// from the current dialog.
String get goToSettings => Intl.message('Go to settings',
desc: 'Message shown on a button that the user can click to go to '
'settings pages from the current dialog. Maximum 30 characters.');
/// Message advising the user to re-enable biometrics on their device.
/// It shows in a dialog on iOS.
String get iOSLockOut => Intl.message(
'Biometric authentication is disabled. Please lock and unlock your screen to '
'enable it.',
desc: 'Message advising the user to re-enable biometrics on their device.');
/// Message advising the user to go to the settings and configure Biometrics
/// for their device.
String get iOSGoToSettingsDescription => Intl.message(
'Biometric authentication is not set up on your device. Please either enable '
'Touch ID or Face ID on your phone.',
desc:
'Message advising the user to go to the settings and configure Biometrics '
'for their device.');
/// Message shown on a button that the user can click to leave the current
/// dialog.
String get iOSOkButton => Intl.message('OK',
desc: 'Message showed on a button that the user can click to leave the '
'current dialog. Maximum 30 characters.');
| packages/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart/0 | {
"file_path": "packages/packages/local_auth/local_auth_darwin/lib/types/auth_messages_ios.dart",
"repo_id": "packages",
"token_count": 1193
} | 1,105 |
name: local_auth_platform_interface
description: A common platform interface for the local_auth plugin.
repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_platform_interface
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22
# NOTE: We strongly prefer non-breaking changes, even at the expense of a
# less-clean API. See https://flutter.dev/go/platform-interface-breaking-changes
version: 1.0.10
environment:
sdk: ^3.1.0
flutter: ">=3.13.0"
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.7
dev_dependencies:
flutter_test:
sdk: flutter
mockito: 5.4.4
topics:
- authentication
- biometrics
- local-auth
| packages/packages/local_auth/local_auth_platform_interface/pubspec.yaml/0 | {
"file_path": "packages/packages/local_auth/local_auth_platform_interface/pubspec.yaml",
"repo_id": "packages",
"token_count": 273
} | 1,106 |
// 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:metrics_center/src/common.dart';
import 'package:metrics_center/src/constants.dart';
import 'package:metrics_center/src/google_benchmark.dart';
import 'common.dart';
import 'utility.dart';
void main() {
test('GoogleBenchmarkParser parses example json.', () async {
final List<MetricPoint> points =
await GoogleBenchmarkParser.parse('test/example_google_benchmark.json');
expect(points.length, 9);
expectSetMatch(
points.map((MetricPoint p) => p.value),
<double>[101, 101, 4460, 4460, 6548, 6548, 3.8, 3.89, 4.89],
);
expectSetMatch(
points.map((MetricPoint p) => p.tags[kSubResultKey]),
<String>[
'cpu_time',
'real_time',
'cpu_coefficient',
'real_coefficient',
'rms',
],
);
expectSetMatch(
points.map((MetricPoint p) => p.tags[kNameKey]),
<String>[
'BM_PaintRecordInit',
'SkParagraphFixture/ShortLayout',
'SkParagraphFixture/TextBigO_BigO',
'ParagraphFixture/TextBigO_BigO',
'ParagraphFixture/TextBigO_RMS',
],
);
for (final MetricPoint p in points) {
expect(p.tags.containsKey('host_name'), false);
expect(p.tags.containsKey('load_avg'), false);
expect(p.tags.containsKey('caches'), false);
expect(p.tags.containsKey('executable'), true);
}
});
}
| packages/packages/metrics_center/test/google_benchmark_test.dart/0 | {
"file_path": "packages/packages/metrics_center/test/google_benchmark_test.dart",
"repo_id": "packages",
"token_count": 643
} | 1,107 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'constants.dart';
import 'resource_record.dart';
// Offsets into the header. See https://tools.ietf.org/html/rfc1035.
const int _kIdOffset = 0;
const int _kFlagsOffset = 2;
const int _kQdcountOffset = 4;
const int _kAncountOffset = 6;
const int _kNscountOffset = 8;
const int _kArcountOffset = 10;
const int _kHeaderSize = 12;
/// Processes a DNS query name into a list of parts.
///
/// Will attempt to append 'local' if the name is something like '_http._tcp',
/// and '._tcp.local' if name is something like '_http'.
List<String> processDnsNameParts(String name) {
final List<String> parts = name.split('.');
if (parts.length == 1) {
return <String>[parts[0], '_tcp', 'local'];
} else if (parts.length == 2 && parts[1].startsWith('_')) {
return <String>[parts[0], parts[1], 'local'];
}
return parts;
}
/// Encode an mDNS query packet.
///
/// The [type] parameter must be a valid [ResourceRecordType] value. The
/// [multicast] parameter must not be null.
///
/// This is a low level API; most consumers should prefer
/// [ResourceRecordQuery.encode], which offers some convenience wrappers around
/// selecting the correct [type] and setting the [name] parameter correctly.
List<int> encodeMDnsQuery(
String name, {
int type = ResourceRecordType.addressIPv4,
bool multicast = true,
}) {
assert(ResourceRecordType.debugAssertValid(type));
final List<String> nameParts = processDnsNameParts(name);
final List<List<int>> rawNameParts =
nameParts.map<List<int>>((String part) => utf8.encode(part)).toList();
// Calculate the size of the packet.
int size = _kHeaderSize;
for (int i = 0; i < rawNameParts.length; i++) {
size += 1 + rawNameParts[i].length;
}
size += 1; // End with empty part
size += 4; // Trailer (QTYPE and QCLASS).
final Uint8List data = Uint8List(size);
final ByteData packetByteData = ByteData.view(data.buffer);
// Query identifier - just use 0.
packetByteData.setUint16(_kIdOffset, 0);
// Flags - 0 for query.
packetByteData.setUint16(_kFlagsOffset, 0);
// Query count.
packetByteData.setUint16(_kQdcountOffset, 1);
// Number of answers - 0 for query.
packetByteData.setUint16(_kAncountOffset, 0);
// Number of name server records - 0 for query.
packetByteData.setUint16(_kNscountOffset, 0);
// Number of resource records - 0 for query.
packetByteData.setUint16(_kArcountOffset, 0);
int offset = _kHeaderSize;
for (int i = 0; i < rawNameParts.length; i++) {
data[offset++] = rawNameParts[i].length;
data.setRange(offset, offset + rawNameParts[i].length, rawNameParts[i]);
offset += rawNameParts[i].length;
}
data[offset] = 0; // Empty part.
offset++;
packetByteData.setUint16(offset, type); // QTYPE.
offset += 2;
packetByteData.setUint16(
offset,
ResourceRecordClass.internet |
(multicast ? QuestionType.multicast : QuestionType.unicast));
return data;
}
/// Result of reading a Fully Qualified Domain Name (FQDN).
class _FQDNReadResult {
/// Creates a new FQDN read result.
_FQDNReadResult(this.fqdnParts, this.bytesRead);
/// The raw parts of the FQDN.
final List<String> fqdnParts;
/// The bytes consumed from the packet for this FQDN.
final int bytesRead;
/// Returns the Fully Qualified Domain Name.
String get fqdn => fqdnParts.join('.');
@override
String toString() => fqdn;
}
/// Reads a FQDN from raw packet data.
String readFQDN(List<int> packet, [int offset = 0]) {
final Uint8List data =
packet is Uint8List ? packet : Uint8List.fromList(packet);
final ByteData byteData = ByteData.view(data.buffer);
return _readFQDN(data, byteData, offset, data.length).fqdn;
}
// Read a FQDN at the given offset. Returns a pair with the FQDN
// parts and the number of bytes consumed.
//
// If decoding fails (e.g. due to an invalid packet) `null` is returned.
_FQDNReadResult _readFQDN(
Uint8List data, ByteData byteData, int offset, int length) {
void checkLength(int required) {
if (length < required) {
throw MDnsDecodeException(required);
}
}
final List<String> parts = <String>[];
final int prevOffset = offset;
while (true) {
// At least one byte is required.
checkLength(offset + 1);
// Check for compressed.
if (data[offset] & 0xc0 == 0xc0) {
// At least two bytes are required for a compressed FQDN.
checkLength(offset + 2);
// A compressed FQDN has a new offset in the lower 14 bits.
final _FQDNReadResult result = _readFQDN(
data, byteData, byteData.getUint16(offset) & ~0xc000, length);
parts.addAll(result.fqdnParts);
offset += 2;
break;
} else {
// A normal FQDN part has a length and a UTF-8 encoded name
// part. If the length is 0 this is the end of the FQDN.
final int partLength = data[offset];
offset++;
if (partLength > 0) {
checkLength(offset + partLength);
final Uint8List partBytes =
Uint8List.view(data.buffer, offset, partLength);
offset += partLength;
// According to the RFC, this is supposed to be utf-8 encoded, but
// we should continue decoding even if it isn't to avoid dropping the
// rest of the data, which might still be useful.
parts.add(utf8.decode(partBytes, allowMalformed: true));
} else {
break;
}
}
}
return _FQDNReadResult(parts, offset - prevOffset);
}
/// Decode an mDNS query packet.
///
/// If decoding fails (e.g. due to an invalid packet), `null` is returned.
///
/// See https://tools.ietf.org/html/rfc1035 for format.
ResourceRecordQuery? decodeMDnsQuery(List<int> packet) {
final int length = packet.length;
if (length < _kHeaderSize) {
return null;
}
final Uint8List data =
packet is Uint8List ? packet : Uint8List.fromList(packet);
final ByteData packetBytes = ByteData.view(data.buffer);
// Check whether it's a query.
final int flags = packetBytes.getUint16(_kFlagsOffset);
if (flags != 0) {
return null;
}
final int questionCount = packetBytes.getUint16(_kQdcountOffset);
if (questionCount == 0) {
return null;
}
final _FQDNReadResult fqdn =
_readFQDN(data, packetBytes, _kHeaderSize, data.length);
int offset = _kHeaderSize + fqdn.bytesRead;
final int type = packetBytes.getUint16(offset);
offset += 2;
final int queryType = packetBytes.getUint16(offset) & 0x8000;
return ResourceRecordQuery(type, fqdn.fqdn, queryType);
}
/// Decode an mDNS response packet.
///
/// If decoding fails (e.g. due to an invalid packet) `null` is returned.
///
/// See https://tools.ietf.org/html/rfc1035 for the format.
List<ResourceRecord>? decodeMDnsResponse(List<int> packet) {
final int length = packet.length;
if (length < _kHeaderSize) {
return null;
}
final Uint8List data =
packet is Uint8List ? packet : Uint8List.fromList(packet);
final ByteData packetBytes = ByteData.view(data.buffer);
final int answerCount = packetBytes.getUint16(_kAncountOffset);
final int authorityCount = packetBytes.getUint16(_kNscountOffset);
final int additionalCount = packetBytes.getUint16(_kArcountOffset);
final int remainingCount = answerCount + authorityCount + additionalCount;
if (remainingCount == 0) {
return null;
}
final int questionCount = packetBytes.getUint16(_kQdcountOffset);
int offset = _kHeaderSize;
void checkLength(int required) {
if (length < required) {
throw MDnsDecodeException(required);
}
}
ResourceRecord? readResourceRecord() {
// First read the FQDN.
final _FQDNReadResult result = _readFQDN(data, packetBytes, offset, length);
final String fqdn = result.fqdn;
offset += result.bytesRead;
checkLength(offset + 2);
final int type = packetBytes.getUint16(offset);
offset += 2;
// The first bit of the rrclass field is set to indicate that the answer is
// unique and the querier should flush the cached answer for this name
// (RFC 6762, Sec. 10.2). We ignore it for now since we don't cache answers.
checkLength(offset + 2);
final int resourceRecordClass = packetBytes.getUint16(offset) & 0x7fff;
if (resourceRecordClass != ResourceRecordClass.internet) {
// We do not support other classes.
return null;
}
offset += 2;
checkLength(offset + 4);
final int ttl = packetBytes.getInt32(offset);
offset += 4;
checkLength(offset + 2);
final int readDataLength = packetBytes.getUint16(offset);
offset += 2;
final int validUntil = DateTime.now().millisecondsSinceEpoch + ttl * 1000;
switch (type) {
case ResourceRecordType.addressIPv4:
checkLength(offset + readDataLength);
final StringBuffer addr = StringBuffer();
final int stop = offset + readDataLength;
addr.write(packetBytes.getUint8(offset));
offset++;
for (; offset < stop; offset++) {
addr.write('.');
addr.write(packetBytes.getUint8(offset));
}
return IPAddressResourceRecord(fqdn, validUntil,
address: InternetAddress(addr.toString()));
case ResourceRecordType.addressIPv6:
checkLength(offset + readDataLength);
final StringBuffer addr = StringBuffer();
final int stop = offset + readDataLength;
addr.write(packetBytes.getUint16(offset).toRadixString(16));
offset += 2;
for (; offset < stop; offset += 2) {
addr.write(':');
addr.write(packetBytes.getUint16(offset).toRadixString(16));
}
return IPAddressResourceRecord(
fqdn,
validUntil,
address: InternetAddress(addr.toString()),
);
case ResourceRecordType.service:
checkLength(offset + 2);
final int priority = packetBytes.getUint16(offset);
offset += 2;
checkLength(offset + 2);
final int weight = packetBytes.getUint16(offset);
offset += 2;
checkLength(offset + 2);
final int port = packetBytes.getUint16(offset);
offset += 2;
final _FQDNReadResult result =
_readFQDN(data, packetBytes, offset, length);
offset += result.bytesRead;
return SrvResourceRecord(
fqdn,
validUntil,
target: result.fqdn,
port: port,
priority: priority,
weight: weight,
);
case ResourceRecordType.serverPointer:
checkLength(offset + readDataLength);
final _FQDNReadResult result =
_readFQDN(data, packetBytes, offset, length);
offset += readDataLength;
return PtrResourceRecord(
fqdn,
validUntil,
domainName: result.fqdn,
);
case ResourceRecordType.text:
checkLength(offset + readDataLength);
// The first byte of the buffer is the length of the first string of
// the TXT record. Further length-prefixed strings may follow. We
// concatenate them with newlines.
final StringBuffer strings = StringBuffer();
int index = 0;
while (index < readDataLength) {
final int txtLength = data[offset + index];
index++;
if (txtLength == 0) {
continue;
}
final String text = utf8.decode(
Uint8List.view(data.buffer, offset + index, txtLength),
allowMalformed: true,
);
strings.writeln(text);
index += txtLength;
}
offset += readDataLength;
return TxtResourceRecord(fqdn, validUntil, text: strings.toString());
default:
checkLength(offset + readDataLength);
offset += readDataLength;
return null;
}
}
// This list can't be fixed length right now because we might get
// resource record types we don't support, and consumers expect this list
// to not have null entries.
final List<ResourceRecord> result = <ResourceRecord>[];
try {
for (int i = 0; i < questionCount; i++) {
final _FQDNReadResult result =
_readFQDN(data, packetBytes, offset, length);
offset += result.bytesRead;
checkLength(offset + 4);
offset += 4;
}
for (int i = 0; i < remainingCount; i++) {
final ResourceRecord? record = readResourceRecord();
if (record != null) {
result.add(record);
}
}
} on MDnsDecodeException {
// If decoding fails return null.
return null;
}
return result;
}
/// This exception is thrown by the decoder when the packet is invalid.
class MDnsDecodeException implements Exception {
/// Creates a new MDnsDecodeException, indicating an error in decoding at the
/// specified [offset].
///
/// The [offset] parameter should not be null.
const MDnsDecodeException(this.offset);
/// The offset in the packet at which the exception occurred.
final int offset;
@override
String toString() => 'Decoding error at $offset';
}
| packages/packages/multicast_dns/lib/src/packet.dart/0 | {
"file_path": "packages/packages/multicast_dns/lib/src/packet.dart",
"repo_id": "packages",
"token_count": 4890
} | 1,108 |
#Tue Jan 07 08:46:39 PST 2020
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
| packages/packages/palette_generator/example/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "packages/packages/palette_generator/example/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "packages",
"token_count": 85
} | 1,109 |
# path_provider
<?code-excerpt path-base="example/lib"?>
[](https://pub.dev/packages/path_provider)
A Flutter plugin for finding commonly used locations on the filesystem.
Supports Android, iOS, Linux, macOS and Windows.
Not all methods are supported on all platforms.
| | Android | iOS | Linux | macOS | Windows |
|-------------|---------|-------|-------|--------|-------------|
| **Support** | SDK 16+ | 12.0+ | Any | 10.14+ | Windows 10+ |
## Usage
To use this plugin, add `path_provider` as a [dependency in your pubspec.yaml file](https://flutter.dev/docs/development/platform-integration/platform-channels).
## Example
<?code-excerpt "readme_excerpts.dart (Example)"?>
```dart
final Directory tempDir = await getTemporaryDirectory();
final Directory appDocumentsDir = await getApplicationDocumentsDirectory();
final Directory? downloadsDir = await getDownloadsDirectory();
```
## Supported platforms and paths
Directories support by platform:
| Directory | Android | iOS | Linux | macOS | Windows |
| :--- | :---: | :---: | :---: | :---: | :---: |
| Temporary | βοΈ | βοΈ | βοΈ | βοΈ | βοΈ |
| Application Support | βοΈ | βοΈ | βοΈ | βοΈ | βοΈ |
| Application Library | βοΈ | βοΈ | βοΈ | βοΈ | βοΈ |
| Application Documents | βοΈ | βοΈ | βοΈ | βοΈ | βοΈ |
| Application Cache | βοΈ | βοΈ | βοΈ | βοΈ | βοΈ |
| External Storage | βοΈ | β | β | βοΈ | βοΈ |
| External Cache Directories | βοΈ | β | β | βοΈ | βοΈ |
| External Storage Directories | βοΈ | β | β | βοΈ | βοΈ |
| Downloads | β | βοΈ | βοΈ | βοΈ | βοΈ |
## Testing
`path_provider` now uses a `PlatformInterface`, meaning that not all platforms share a single `PlatformChannel`-based implementation.
With that change, tests should be updated to mock `PathProviderPlatform` rather than `PlatformChannel`.
See this `path_provider` [test](https://github.com/flutter/packages/blob/main/packages/path_provider/path_provider/test/path_provider_test.dart) for an example.
| packages/packages/path_provider/path_provider/README.md/0 | {
"file_path": "packages/packages/path_provider/path_provider/README.md",
"repo_id": "packages",
"token_count": 663
} | 1,110 |
<?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.app-sandbox</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
</dict>
</plist>
| packages/packages/path_provider/path_provider/example/macos/Runner/DebugProfile.entitlements/0 | {
"file_path": "packages/packages/path_provider/path_provider/example/macos/Runner/DebugProfile.entitlements",
"repo_id": "packages",
"token_count": 184
} | 1,111 |
group 'io.flutter.plugins.pathprovider'
version '1.0-SNAPSHOT'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.1'
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
android {
// Conditional for compatibility with AGP <4.2.
if (project.android.hasProperty("namespace")) {
namespace 'io.flutter.plugins.pathprovider'
}
compileSdk 34
defaultConfig {
minSdkVersion 16
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
lintOptions {
checkAllWarnings true
warningsAsErrors true
disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
testOptions {
unitTests.includeAndroidResources = true
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
}
dependencies {
implementation 'androidx.annotation:annotation:1.7.1'
testImplementation 'junit:junit:4.13.2'
}
| packages/packages/path_provider/path_provider_android/android/build.gradle/0 | {
"file_path": "packages/packages/path_provider/path_provider_android/android/build.gradle",
"repo_id": "packages",
"token_count": 629
} | 1,112 |
// 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 (v9.2.5), 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:path_provider_android/messages.g.dart';
abstract class TestPathProviderApi {
static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding =>
TestDefaultBinaryMessengerBinding.instance;
static const MessageCodec<Object?> codec = StandardMessageCodec();
String? getTemporaryPath();
String? getApplicationSupportPath();
String? getApplicationDocumentsPath();
String? getApplicationCachePath();
String? getExternalStoragePath();
List<String?> getExternalCachePaths();
List<String?> getExternalStoragePaths(StorageDirectory directory);
static void setup(TestPathProviderApi? api,
{BinaryMessenger? binaryMessenger}) {
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getTemporaryPath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final String? output = api.getTemporaryPath();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationSupportPath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final String? output = api.getApplicationSupportPath();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationDocumentsPath',
codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final String? output = api.getApplicationDocumentsPath();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getApplicationCachePath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final String? output = api.getApplicationCachePath();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePath', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final String? output = api.getExternalStoragePath();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalCachePaths', codec,
binaryMessenger: binaryMessenger);
if (api == null) {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel, null);
} else {
_testBinaryMessengerBinding!.defaultBinaryMessenger
.setMockDecodedMessageHandler<Object?>(channel,
(Object? message) async {
// ignore message
final List<String?> output = api.getExternalCachePaths();
return <Object?>[output];
});
}
}
{
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
'dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths', 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.PathProviderApi.getExternalStoragePaths was null.');
final List<Object?> args = (message as List<Object?>?)!;
final StorageDirectory? arg_directory =
args[0] == null ? null : StorageDirectory.values[args[0] as int];
assert(arg_directory != null,
'Argument for dev.flutter.pigeon.PathProviderApi.getExternalStoragePaths was null, expected non-null StorageDirectory.');
final List<String?> output =
api.getExternalStoragePaths(arg_directory!);
return <Object?>[output];
});
}
}
}
}
| packages/packages/path_provider/path_provider_android/test/messages_test.g.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_android/test/messages_test.g.dart",
"repo_id": "packages",
"token_count": 2716
} | 1,113 |
// 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:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:path_provider_platform_interface/src/method_channel_path_provider.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('$PathProviderPlatform', () {
test('$MethodChannelPathProvider is the default instance', () {
expect(PathProviderPlatform.instance, isA<MethodChannelPathProvider>());
});
test('getApplicationCachePath throws unimplemented error', () {
final ExtendsPathProviderPlatform pathProviderPlatform =
ExtendsPathProviderPlatform();
expect(
() => pathProviderPlatform.getApplicationCachePath(),
throwsUnimplementedError,
);
});
});
}
class ExtendsPathProviderPlatform extends PathProviderPlatform {}
| packages/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart",
"repo_id": "packages",
"token_count": 314
} | 1,114 |
// 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:win32/win32.dart';
// ignore_for_file: non_constant_identifier_names
// ignore: avoid_classes_with_only_static_members
/// A class containing the GUID references for each of the documented Windows
/// known folders. A property of this class may be passed to the `getPath`
/// method in the [PathProvidersWindows] class to retrieve a known folder from
/// Windows.
class WindowsKnownFolder {
/// The file system directory that is used to store administrative tools for
/// an individual user. The MMC will save customized consoles to this
/// directory, and it will roam with the user.
static String get AdminTools => FOLDERID_AdminTools;
/// The file system directory that acts as a staging area for files waiting to
/// be written to a CD. A typical path is C:\Documents and
/// Settings\username\Local Settings\Application Data\Microsoft\CD Burning.
static String get CDBurning => FOLDERID_CDBurning;
/// The file system directory that contains administrative tools for all users
/// of the computer.
static String get CommonAdminTools => FOLDERID_CommonAdminTools;
/// The file system directory that contains the directories for the common
/// program groups that appear on the Start menu for all users. A typical path
/// is C:\Documents and Settings\All Users\Start Menu\Programs.
static String get CommonPrograms => FOLDERID_CommonPrograms;
/// The file system directory that contains the programs and folders that
/// appear on the Start menu for all users. A typical path is C:\Documents and
/// Settings\All Users\Start Menu.
static String get CommonStartMenu => FOLDERID_CommonStartMenu;
/// The file system directory that contains the programs that appear in the
/// Startup folder for all users. A typical path is C:\Documents and
/// Settings\All Users\Start Menu\Programs\Startup.
static String get CommonStartup => FOLDERID_CommonStartup;
/// The file system directory that contains the templates that are available
/// to all users. A typical path is C:\Documents and Settings\All
/// Users\Templates.
static String get CommonTemplates => FOLDERID_CommonTemplates;
/// The virtual folder that represents My Computer, containing everything on
/// the local computer: storage devices, printers, and Control Panel. The
/// folder can also contain mapped network drives.
static String get ComputerFolder => FOLDERID_ComputerFolder;
/// The virtual folder that represents Network Connections, that contains
/// network and dial-up connections.
static String get ConnectionsFolder => FOLDERID_ConnectionsFolder;
/// The virtual folder that contains icons for the Control Panel applications.
static String get ControlPanelFolder => FOLDERID_ControlPanelFolder;
/// The file system directory that serves as a common repository for Internet
/// cookies. A typical path is C:\Documents and Settings\username\Cookies.
static String get Cookies => FOLDERID_Cookies;
/// The virtual folder that represents the Windows desktop, the root of the
/// namespace.
static String get Desktop => FOLDERID_Desktop;
/// The virtual folder that represents the My Documents desktop item.
static String get Documents => FOLDERID_Documents;
/// The file system directory that serves as a repository for Internet
/// downloads.
static String get Downloads => FOLDERID_Downloads;
/// The file system directory that serves as a common repository for the
/// user's favorite items. A typical path is C:\Documents and
/// Settings\username\Favorites.
static String get Favorites => FOLDERID_Favorites;
/// A virtual folder that contains fonts. A typical path is C:\Windows\Fonts.
static String get Fonts => FOLDERID_Fonts;
/// The file system directory that serves as a common repository for Internet
/// history items.
static String get History => FOLDERID_History;
/// The file system directory that serves as a common repository for temporary
/// Internet files. A typical path is C:\Documents and Settings\username\Local
/// Settings\Temporary Internet Files.
static String get InternetCache => FOLDERID_InternetCache;
/// A virtual folder for Internet Explorer.
static String get InternetFolder => FOLDERID_InternetFolder;
/// The file system directory that serves as a data repository for local
/// (nonroaming) applications. A typical path is C:\Documents and
/// Settings\username\Local Settings\Application Data.
static String get LocalAppData => FOLDERID_LocalAppData;
/// The file system directory that serves as a common repository for music
/// files. A typical path is C:\Documents and Settings\User\My Documents\My
/// Music.
static String get Music => FOLDERID_Music;
/// A file system directory that contains the link objects that may exist in
/// the My Network Places virtual folder. A typical path is C:\Documents and
/// Settings\username\NetHood.
static String get NetHood => FOLDERID_NetHood;
/// The folder that represents other computers in your workgroup.
static String get NetworkFolder => FOLDERID_NetworkFolder;
/// The file system directory that serves as a common repository for image
/// files. A typical path is C:\Documents and Settings\username\My
/// Documents\My Pictures.
static String get Pictures => FOLDERID_Pictures;
/// The file system directory that contains the link objects that can exist in
/// the Printers virtual folder. A typical path is C:\Documents and
/// Settings\username\PrintHood.
static String get PrintHood => FOLDERID_PrintHood;
/// The virtual folder that contains installed printers.
static String get PrintersFolder => FOLDERID_PrintersFolder;
/// The user's profile folder. A typical path is C:\Users\username.
/// Applications should not create files or folders at this level.
static String get Profile => FOLDERID_Profile;
/// The file system directory that contains application data for all users. A
/// typical path is C:\Documents and Settings\All Users\Application Data. This
/// folder is used for application data that is not user specific. For
/// example, an application can store a spell-check dictionary, a database of
/// clip art, or a log file in the CSIDL_COMMON_APPDATA folder. This
/// information will not roam and is available to anyone using the computer.
static String get ProgramData => FOLDERID_ProgramData;
/// The Program Files folder. A typical path is C:\Program Files.
static String get ProgramFiles => FOLDERID_ProgramFiles;
/// The common Program Files folder. A typical path is C:\Program
/// Files\Common.
static String get ProgramFilesCommon => FOLDERID_ProgramFilesCommon;
/// On 64-bit systems, a link to the common Program Files folder. A typical path is
/// C:\Program Files\Common Files.
static String get ProgramFilesCommonX64 => FOLDERID_ProgramFilesCommonX64;
/// On 64-bit systems, a link to the 32-bit common Program Files folder. A
/// typical path is C:\Program Files (x86)\Common Files. On 32-bit systems, a
/// link to the Common Program Files folder.
static String get ProgramFilesCommonX86 => FOLDERID_ProgramFilesCommonX86;
/// On 64-bit systems, a link to the Program Files folder. A typical path is
/// C:\Program Files.
static String get ProgramFilesX64 => FOLDERID_ProgramFilesX64;
/// On 64-bit systems, a link to the 32-bit Program Files folder. A typical
/// path is C:\Program Files (x86). On 32-bit systems, a link to the Common
/// Program Files folder.
static String get ProgramFilesX86 => FOLDERID_ProgramFilesX86;
/// The file system directory that contains the user's program groups (which
/// are themselves file system directories).
static String get Programs => FOLDERID_Programs;
/// The file system directory that contains files and folders that appear on
/// the desktop for all users. A typical path is C:\Documents and Settings\All
/// Users\Desktop.
static String get PublicDesktop => FOLDERID_PublicDesktop;
/// The file system directory that contains documents that are common to all
/// users. A typical path is C:\Documents and Settings\All Users\Documents.
static String get PublicDocuments => FOLDERID_PublicDocuments;
/// The file system directory that serves as a repository for music files
/// common to all users. A typical path is C:\Documents and Settings\All
/// Users\Documents\My Music.
static String get PublicMusic => FOLDERID_PublicMusic;
/// The file system directory that serves as a repository for image files
/// common to all users. A typical path is C:\Documents and Settings\All
/// Users\Documents\My Pictures.
static String get PublicPictures => FOLDERID_PublicPictures;
/// The file system directory that serves as a repository for video files
/// common to all users. A typical path is C:\Documents and Settings\All
/// Users\Documents\My Videos.
static String get PublicVideos => FOLDERID_PublicVideos;
/// The file system directory that contains shortcuts to the user's most
/// recently used documents. A typical path is C:\Documents and
/// Settings\username\My Recent Documents.
static String get Recent => FOLDERID_Recent;
/// The virtual folder that contains the objects in the user's Recycle Bin.
static String get RecycleBinFolder => FOLDERID_RecycleBinFolder;
/// The file system directory that contains resource data. A typical path is
/// C:\Windows\Resources.
static String get ResourceDir => FOLDERID_ResourceDir;
/// The file system directory that serves as a common repository for
/// application-specific data. A typical path is C:\Documents and
/// Settings\username\Application Data.
static String get RoamingAppData => FOLDERID_RoamingAppData;
/// The file system directory that contains Send To menu items. A typical path
/// is C:\Documents and Settings\username\SendTo.
static String get SendTo => FOLDERID_SendTo;
/// The file system directory that contains Start menu items. A typical path
/// is C:\Documents and Settings\username\Start Menu.
static String get StartMenu => FOLDERID_StartMenu;
/// The file system directory that corresponds to the user's Startup program
/// group. The system starts these programs whenever the associated user logs
/// on. A typical path is C:\Documents and Settings\username\Start
/// Menu\Programs\Startup.
static String get Startup => FOLDERID_Startup;
/// The Windows System folder. A typical path is C:\Windows\System32.
static String get System => FOLDERID_System;
/// The 32-bit Windows System folder. On 32-bit systems, this is typically
/// C:\Windows\system32. On 64-bit systems, this is typically
/// C:\Windows\syswow64.
static String get SystemX86 => FOLDERID_SystemX86;
/// The file system directory that serves as a common repository for document
/// templates. A typical path is C:\Documents and Settings\username\Templates.
static String get Templates => FOLDERID_Templates;
/// The file system directory that serves as a common repository for video
/// files. A typical path is C:\Documents and Settings\username\My
/// Documents\My Videos.
static String get Videos => FOLDERID_Videos;
/// The Windows directory or SYSROOT. This corresponds to the %windir% or
/// %SYSTEMROOT% environment variables. A typical path is C:\Windows.
static String get Windows => FOLDERID_Windows;
}
| packages/packages/path_provider/path_provider_windows/lib/src/folders.dart/0 | {
"file_path": "packages/packages/path_provider/path_provider_windows/lib/src/folders.dart",
"repo_id": "packages",
"token_count": 2895
} | 1,115 |
#!/bin/bash
# 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.
###############################################################################
# A tool that helps you check the Pigeon output for a given file across
# different versions of Pigeon.
#
# The comparison will be made between the currently checked out sha and the one
# provided as an argument.
#
# usage: ./diff_tool.sh <sha for commit to test against> <path to pigeon file>
###############################################################################
xHash=$1
pigeonPath=$2
diffTool="diff -ru"
gitTool="git -c advice.detachedHead=false"
generate_everything() {
local inputPath=$1
local outputDir=$2
pub run pigeon \
--input "$inputPath" \
--dart_out "$outputDir/dart.dart" \
--java_out "$outputDir/java.dart" \
--objc_header_out "$outputDir/objc.h" \
--objc_source_out "$outputDir/objc.m"
}
yHash=$(git rev-parse HEAD)
xDir=$(mktemp -d -t $xHash)
yDir=$(mktemp -d -t $yHash)
inputPath=$yDir/input.dart
cp "$pigeonPath" "$inputPath"
$gitTool checkout $xHash 1> /dev/null
generate_everything $inputPath $xDir
$gitTool checkout $yHash 1> /dev/null
generate_everything $inputPath $yDir
$diffTool "$yDir" "$xDir"
rm -rf "$yDir"
rm -rf "$xDir"
| packages/packages/pigeon/diff_tool.sh/0 | {
"file_path": "packages/packages/pigeon/diff_tool.sh",
"repo_id": "packages",
"token_count": 438
} | 1,116 |
// 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 '../generator_tools.dart';
/// Creates the `InstanceManager` with the passed string values.
String instanceManagerTemplate({
required Iterable<String> allProxyApiNames,
}) {
final Iterable<String> apiHandlerSetUps = allProxyApiNames.map(
(String name) {
return '$name.${classMemberNamePrefix}setUpMessageHandlers(${classMemberNamePrefix}instanceManager: instanceManager);';
},
);
return '''
/// Maintains instances used to communicate with the native objects they
/// represent.
///
/// Added instances are stored as weak references and their copies are stored
/// as strong references to maintain access to their variables and callback
/// methods. Both are stored with the same identifier.
///
/// When a weak referenced instance becomes inaccessible,
/// [onWeakReferenceRemoved] is called with its associated identifier.
///
/// If an instance is retrieved and has the possibility to be used,
/// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference
/// is added as a weak reference with the same identifier. This prevents a
/// scenario where the weak referenced instance was released and then later
/// returned by the host platform.
class $instanceManagerClassName {
/// Constructs a [$instanceManagerClassName].
$instanceManagerClassName({required void Function(int) onWeakReferenceRemoved}) {
this.onWeakReferenceRemoved = (int identifier) {
_weakInstances.remove(identifier);
onWeakReferenceRemoved(identifier);
};
_finalizer = Finalizer<int>(this.onWeakReferenceRemoved);
}
// Identifiers are locked to a specific range to avoid collisions with objects
// created simultaneously by the host platform.
// Host uses identifiers >= 2^16 and Dart is expected to use values n where,
// 0 <= n < 2^16.
static const int _maxDartCreatedIdentifier = 65536;
/// The default [$instanceManagerClassName] used by ProxyApis.
///
/// On creation, this manager makes a call to clear the native
/// InstanceManager. This is to prevent identifier conflicts after a host
/// restart.
static final $instanceManagerClassName instance = _initInstance();
// Expando is used because it doesn't prevent its keys from becoming
// inaccessible. This allows the manager to efficiently retrieve an identifier
// of an instance without holding a strong reference to that instance.
//
// It also doesn't use `==` to search for identifiers, which would lead to an
// infinite loop when comparing an object to its copy. (i.e. which was caused
// by calling instanceManager.getIdentifier() inside of `==` while this was a
// HashMap).
final Expando<int> _identifiers = Expando<int>();
final Map<int, WeakReference<$proxyApiBaseClassName>> _weakInstances =
<int, WeakReference<$proxyApiBaseClassName>>{};
final Map<int, $proxyApiBaseClassName> _strongInstances = <int, $proxyApiBaseClassName>{};
late final Finalizer<int> _finalizer;
int _nextIdentifier = 0;
/// Called when a weak referenced instance is removed by [removeWeakReference]
/// or becomes inaccessible.
late final void Function(int) onWeakReferenceRemoved;
static $instanceManagerClassName _initInstance() {
WidgetsFlutterBinding.ensureInitialized();
final _${instanceManagerClassName}Api api = _${instanceManagerClassName}Api();
// Clears the native `$instanceManagerClassName` on the initial use of the Dart one.
api.clear();
final $instanceManagerClassName instanceManager = $instanceManagerClassName(
onWeakReferenceRemoved: (int identifier) {
api.removeStrongReference(identifier);
},
);
_${instanceManagerClassName}Api.setUpMessageHandlers(instanceManager: instanceManager);
${apiHandlerSetUps.join('\n\t\t')}
return instanceManager;
}
/// Adds a new instance that was instantiated by Dart.
///
/// In other words, Dart wants to add a new instance that will represent
/// an object that will be instantiated on the host platform.
///
/// Throws assertion error if the instance has already been added.
///
/// Returns the randomly generated id of the [instance] added.
int addDartCreatedInstance($proxyApiBaseClassName instance) {
final int identifier = _nextUniqueIdentifier();
_addInstanceWithIdentifier(instance, identifier);
return identifier;
}
/// Removes the instance, if present, and call [onWeakReferenceRemoved] with
/// its identifier.
///
/// Returns the identifier associated with the removed instance. Otherwise,
/// `null` if the instance was not found in this manager.
///
/// This does not remove the strong referenced instance associated with
/// [instance]. This can be done with [remove].
int? removeWeakReference($proxyApiBaseClassName instance) {
final int? identifier = getIdentifier(instance);
if (identifier == null) {
return null;
}
_identifiers[instance] = null;
_finalizer.detach(instance);
onWeakReferenceRemoved(identifier);
return identifier;
}
/// Removes [identifier] and its associated strongly referenced instance, if
/// present, from the manager.
///
/// Returns the strong referenced instance associated with [identifier] before
/// it was removed. Returns `null` if [identifier] was not associated with
/// any strong reference.
///
/// This does not remove the weak referenced instance associated with
/// [identifier]. This can be done with [removeWeakReference].
T? remove<T extends $proxyApiBaseClassName>(int identifier) {
return _strongInstances.remove(identifier) as T?;
}
/// Retrieves the instance associated with identifier.
///
/// The value returned is chosen from the following order:
///
/// 1. A weakly referenced instance associated with identifier.
/// 2. If the only instance associated with identifier is a strongly
/// referenced instance, a copy of the instance is added as a weak reference
/// with the same identifier. Returning the newly created copy.
/// 3. If no instance is associated with identifier, returns null.
///
/// This method also expects the host `InstanceManager` to have a strong
/// reference to the instance the identifier is associated with.
T? getInstanceWithWeakReference<T extends $proxyApiBaseClassName>(int identifier) {
final $proxyApiBaseClassName? weakInstance = _weakInstances[identifier]?.target;
if (weakInstance == null) {
final $proxyApiBaseClassName? strongInstance = _strongInstances[identifier];
if (strongInstance != null) {
final $proxyApiBaseClassName copy = strongInstance.${classMemberNamePrefix}copy();
_identifiers[copy] = identifier;
_weakInstances[identifier] = WeakReference<$proxyApiBaseClassName>(copy);
_finalizer.attach(copy, identifier, detach: copy);
return copy as T;
}
return strongInstance as T?;
}
return weakInstance as T;
}
/// Retrieves the identifier associated with instance.
int? getIdentifier($proxyApiBaseClassName instance) {
return _identifiers[instance];
}
/// Adds a new instance that was instantiated by the host platform.
///
/// In other words, the host platform wants to add a new instance that
/// represents an object on the host platform. Stored with [identifier].
///
/// Throws assertion error if the instance or its identifier has already been
/// added.
///
/// Returns unique identifier of the [instance] added.
void addHostCreatedInstance($proxyApiBaseClassName instance, int identifier) {
_addInstanceWithIdentifier(instance, identifier);
}
void _addInstanceWithIdentifier($proxyApiBaseClassName instance, int identifier) {
assert(!containsIdentifier(identifier));
assert(getIdentifier(instance) == null);
assert(identifier >= 0);
_identifiers[instance] = identifier;
_weakInstances[identifier] = WeakReference<$proxyApiBaseClassName>(instance);
_finalizer.attach(instance, identifier, detach: instance);
final $proxyApiBaseClassName copy = instance.${classMemberNamePrefix}copy();
_identifiers[copy] = identifier;
_strongInstances[identifier] = copy;
}
/// Whether this manager contains the given [identifier].
bool containsIdentifier(int identifier) {
return _weakInstances.containsKey(identifier) ||
_strongInstances.containsKey(identifier);
}
int _nextUniqueIdentifier() {
late int identifier;
do {
identifier = _nextIdentifier;
_nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier;
} while (containsIdentifier(identifier));
return identifier;
}
}
''';
}
/// Creates the `InstanceManagerApi` with the passed string values.
String instanceManagerApiTemplate({
required String dartPackageName,
required String pigeonChannelCodecVarName,
}) {
const String apiName = '${instanceManagerClassName}Api';
final String removeStrongReferenceName = makeChannelNameWithStrings(
apiName: apiName,
methodName: 'removeStrongReference',
dartPackageName: dartPackageName,
);
final String clearName = makeChannelNameWithStrings(
apiName: apiName,
methodName: 'clear',
dartPackageName: dartPackageName,
);
return '''
/// Generated API for managing the Dart and native `$instanceManagerClassName`s.
class _$apiName {
/// Constructor for [_$apiName].
_$apiName({BinaryMessenger? binaryMessenger})
: _binaryMessenger = binaryMessenger;
final BinaryMessenger? _binaryMessenger;
static const MessageCodec<Object?> $pigeonChannelCodecVarName =
StandardMessageCodec();
static void setUpMessageHandlers({
BinaryMessenger? binaryMessenger,
$instanceManagerClassName? instanceManager,
}) {
const String channelName =
r'$removeStrongReferenceName';
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
channelName,
$pigeonChannelCodecVarName,
binaryMessenger: binaryMessenger,
);
channel.setMessageHandler((Object? message) async {
assert(
message != null,
'Argument for \$channelName was null.',
);
final int? identifier = message as int?;
assert(
identifier != null,
r'Argument for \$channelName, expected non-null int.',
);
(instanceManager ?? $instanceManagerClassName.instance).remove(identifier!);
return;
});
}
Future<void> removeStrongReference(int identifier) async {
const String channelName =
r'$removeStrongReferenceName';
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
channelName,
$pigeonChannelCodecVarName,
binaryMessenger: _binaryMessenger,
);
final List<Object?>? replyList =
await channel.send(identifier) as List<Object?>?;
if (replyList == null) {
throw _createConnectionError(channelName);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
/// Clear the native `$instanceManagerClassName`.
///
/// This is typically called after a hot restart.
Future<void> clear() async {
const String channelName =
r'$clearName';
final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>(
channelName,
$pigeonChannelCodecVarName,
binaryMessenger: _binaryMessenger,
);
final List<Object?>? replyList = await channel.send(null) as List<Object?>?;
if (replyList == null) {
throw _createConnectionError(channelName);
} else if (replyList.length > 1) {
throw PlatformException(
code: replyList[0]! as String,
message: replyList[1] as String?,
details: replyList[2],
);
} else {
return;
}
}
}''';
}
/// The base class for all ProxyApis.
///
/// All Dart classes generated as a ProxyApi extends this one.
const String proxyApiBaseClass = '''
/// An immutable object that serves as the base class for all ProxyApis and
/// can provide functional copies of itself.
///
/// All implementers are expected to be [immutable] as defined by the annotation
/// and override [${classMemberNamePrefix}copy] returning an instance of itself.
@immutable
abstract class $proxyApiBaseClassName {
/// Construct a [$proxyApiBaseClassName].
$proxyApiBaseClassName({
this.$_proxyApiBaseClassMessengerVarName,
$instanceManagerClassName? $_proxyApiBaseClassInstanceManagerVarName,
}) : $_proxyApiBaseClassInstanceManagerVarName =
$_proxyApiBaseClassInstanceManagerVarName ?? $instanceManagerClassName.instance;
/// Sends and receives binary data across the Flutter platform barrier.
///
/// If it is null, the default BinaryMessenger will be used, which routes to
/// the host platform.
@protected
final BinaryMessenger? $_proxyApiBaseClassMessengerVarName;
/// Maintains instances stored to communicate with native language objects.
@protected
final $instanceManagerClassName $_proxyApiBaseClassInstanceManagerVarName;
/// Instantiates and returns a functionally identical object to oneself.
///
/// Outside of tests, this method should only ever be called by
/// [$instanceManagerClassName].
///
/// Subclasses should always override their parent's implementation of this
/// method.
@protected
$proxyApiBaseClassName ${classMemberNamePrefix}copy();
}
''';
/// The base codec for ProxyApis.
///
/// All generated Dart proxy apis should use this codec or extend it. This codec
/// adds support to convert instances to their corresponding identifier from an
/// `InstanceManager` and vice versa.
const String proxyApiBaseCodec = '''
class $_proxyApiCodecName extends StandardMessageCodec {
const $_proxyApiCodecName(this.instanceManager);
final $instanceManagerClassName instanceManager;
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is $proxyApiBaseClassName) {
buffer.putUint8(128);
writeValue(buffer, instanceManager.getIdentifier(value));
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return instanceManager
.getInstanceWithWeakReference(readValue(buffer)! as int);
default:
return super.readValueOfType(type, buffer);
}
}
}
''';
/// Name of the base class of all ProxyApis.
const String proxyApiBaseClassName = '${classNamePrefix}ProxyApiBaseClass';
const String _proxyApiBaseClassMessengerVarName =
'${classMemberNamePrefix}binaryMessenger';
const String _proxyApiBaseClassInstanceManagerVarName =
'${classMemberNamePrefix}instanceManager';
const String _proxyApiCodecName = '_${classNamePrefix}ProxyApiBaseCodec';
| packages/packages/pigeon/lib/dart/templates.dart/0 | {
"file_path": "packages/packages/pigeon/lib/dart/templates.dart",
"repo_id": "packages",
"token_count": 4491
} | 1,117 |
// 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(
objcOptions: ObjcOptions(prefix: 'PGN'),
))
/// This comment is to test enum documentation comments.
enum EnumState {
/// This comment is to test enum member (Pending) documentation comments.
Pending,
/// This comment is to test enum member (Success) documentation comments.
Success,
/// This comment is to test enum member (Error) documentation comments.
Error,
/// This comment is to test enum member (SnakeCase) documentation comments.
SnakeCase,
}
/// This comment is to test class documentation comments.
class DataWithEnum {
/// This comment is to test field documentation comments.
EnumState? state;
}
@HostApi()
/// This comment is to test api documentation comments.
abstract class EnumApi2Host {
/// This comment is to test method documentation comments.
DataWithEnum echo(DataWithEnum data);
}
@FlutterApi()
/// This comment is to test api documentation comments.
abstract class EnumApi2Flutter {
/// This comment is to test method documentation comments.
DataWithEnum echo(DataWithEnum data);
}
| packages/packages/pigeon/pigeons/enum.dart/0 | {
"file_path": "packages/packages/pigeon/pigeons/enum.dart",
"repo_id": "packages",
"token_count": 353
} | 1,118 |
// 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;
NS_ASSUME_NONNULL_BEGIN
typedef id _Nullable (^HandlerBinaryMessengerHandler)(NSArray *_Nonnull args);
/// A FlutterBinaryMessenger that calls a supplied method when a call is
/// invoked.
@interface HandlerBinaryMessenger : NSObject <FlutterBinaryMessenger>
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithCodec:(NSObject<FlutterMessageCodec> *)codec
handler:(HandlerBinaryMessengerHandler)handler;
@end
NS_ASSUME_NONNULL_END
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/HandlerBinaryMessenger.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/HandlerBinaryMessenger.h",
"repo_id": "packages",
"token_count": 224
} | 1,119 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "packages",
"token_count": 32
} | 1,120 |
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint alternate_language_test_plugin.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'alternate_language_test_plugin'
s.version = '0.0.1'
s.summary = 'Alternate-language Pigeon test plugin'
s.description = <<-DESC
A plugin to test Pigeon generation for secondary languages (e.g., Java, Objective-C).
DESC
s.homepage = 'http://example.com'
s.license = { :type => 'BSD', :file => '../../../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/pigeon' }
s.source_files = 'Classes/**/*'
s.public_header_files = 'Classes/**/*.h'
s.dependency 'Flutter'
s.platform = :ios, '12.0'
s.xcconfig = {
'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift',
'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift',
}
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
end
| packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/alternate_language_test_plugin.podspec/0 | {
"file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/ios/alternate_language_test_plugin.podspec",
"repo_id": "packages",
"token_count": 552
} | 1,121 |
// 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".',
);
}
class BackgroundApi2Host {
/// Constructor for [BackgroundApi2Host]. 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.
BackgroundApi2Host({BinaryMessenger? binaryMessenger})
: __pigeon_binaryMessenger = binaryMessenger;
final BinaryMessenger? __pigeon_binaryMessenger;
static const MessageCodec<Object?> pigeonChannelCodec =
StandardMessageCodec();
Future<int> add(int x, int y) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.pigeon_integration_tests.BackgroundApi2Host.add';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[x, y]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as int?)!;
}
}
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart",
"repo_id": "packages",
"token_count": 890
} | 1,122 |
// Mocks generated by Mockito 5.4.1 from annotations
// in shared_test_plugin_code/test/multiple_arity_test.dart.
// Do not manually edit this file.
// @dart=2.19
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:typed_data' as _i4;
import 'dart:ui' as _i5;
import 'package:flutter/src/services/binary_messenger.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
/// A class which mocks [BinaryMessenger].
///
/// See the documentation for Mockito's code generation for more information.
class MockBinaryMessenger extends _i1.Mock implements _i2.BinaryMessenger {
MockBinaryMessenger() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<void> handlePlatformMessage(
String? channel,
_i4.ByteData? data,
_i5.PlatformMessageResponseCallback? callback,
) =>
(super.noSuchMethod(
Invocation.method(
#handlePlatformMessage,
[
channel,
data,
callback,
],
),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
) as _i3.Future<void>);
@override
_i3.Future<_i4.ByteData?>? send(
String? channel,
_i4.ByteData? message,
) =>
(super.noSuchMethod(Invocation.method(
#send,
[
channel,
message,
],
)) as _i3.Future<_i4.ByteData?>?);
@override
void setMessageHandler(
String? channel,
_i2.MessageHandler? handler,
) =>
super.noSuchMethod(
Invocation.method(
#setMessageHandler,
[
channel,
handler,
],
),
returnValueForMissingStub: null,
);
}
| packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.mocks.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.mocks.dart",
"repo_id": "packages",
"token_count": 942
} | 1,123 |
// 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:shared_test_plugin_code/integration_tests.dart';
void main() => runPigeonIntegrationTests(_getTarget());
TargetGenerator _getTarget() {
if (Platform.isAndroid) {
return TargetGenerator.kotlin;
}
if (Platform.isIOS || Platform.isMacOS) {
return TargetGenerator.swift;
}
if (Platform.isWindows) {
return TargetGenerator.cpp;
}
throw UnimplementedError('Unsupported target.');
}
| packages/packages/pigeon/platform_tests/test_plugin/example/integration_test/test.dart/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/integration_test/test.dart",
"repo_id": "packages",
"token_count": 201
} | 1,124 |
// 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 XCTest
@testable import test_plugin
/// Tests NSNull is correctly handled by `nilOrValue` helper, by manually setting nullable fields to NSNull.
final class NSNullFieldTests: XCTestCase {
func testNSNull_nullListToCustomStructField() throws {
let reply = NullFieldsSearchReply(
result: nil,
error: nil,
indices: nil,
request: nil,
type: nil)
var list = reply.toList()
// request field
list[3] = NSNull()
let copy = NullFieldsSearchReply.fromList(list)
XCTAssertNotNil(copy)
XCTAssertNil(copy!.request)
}
func testNSNull_nullListField() {
let reply = NullFieldsSearchReply(
result: nil,
error: nil,
indices: nil,
request: nil,
type: nil)
var list = reply.toList()
// indices field
list[2] = NSNull()
let copy = NullFieldsSearchReply.fromList(list)
XCTAssertNotNil(copy)
XCTAssertNil(copy!.indices)
}
func testNSNull_nullBasicFields() throws {
let reply = NullFieldsSearchReply(
result: nil,
error: nil,
indices: nil,
request: nil,
type: nil)
var list = reply.toList()
// result field
list[0] = NSNull()
// error field
list[1] = NSNull()
// type field
list[4] = NSNull()
let copy = NullFieldsSearchReply.fromList(list)
XCTAssertNotNil(copy)
XCTAssertNil(copy!.result)
XCTAssertNil(copy!.error)
XCTAssertNil(copy!.type)
}
}
| packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift",
"repo_id": "packages",
"token_count": 642
} | 1,125 |
name: test_plugin
description: Pigeon test harness for primary 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.test_plugin
pluginClass: TestPlugin
ios:
pluginClass: TestPlugin
macos:
pluginClass: TestPlugin
windows:
pluginClass: TestPluginCApi
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
| packages/packages/pigeon/platform_tests/test_plugin/pubspec.yaml/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/pubspec.yaml",
"repo_id": "packages",
"token_count": 225
} | 1,126 |
// 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.
#ifndef PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_FAKE_HOST_MESSENGER_H_
#define PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_FAKE_HOST_MESSENGER_H_
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/message_codec.h>
#include <map>
namespace testing {
typedef std::function<void(const flutter::EncodableValue& reply)>
HostMessageReply;
// A BinaryMessenger that allows tests to act as the engine to call host APIs.
class FakeHostMessenger : public flutter::BinaryMessenger {
public:
// Creates an messenger that can send and receive responses with the given
// codec.
FakeHostMessenger(
const flutter::MessageCodec<flutter::EncodableValue>* codec);
virtual ~FakeHostMessenger();
// Calls the registered handler for the given channel, and calls reply_handler
// with the response.
//
// This allows a test to simulate a message from the Dart side, exercising the
// encoding and decoding logic generated for a host API.
void SendHostMessage(const std::string& channel,
const flutter::EncodableValue& message,
HostMessageReply reply_handler);
// flutter::BinaryMessenger:
void Send(const std::string& channel, const uint8_t* message,
size_t message_size,
flutter::BinaryReply reply = nullptr) const override;
void SetMessageHandler(const std::string& channel,
flutter::BinaryMessageHandler handler) override;
private:
const flutter::MessageCodec<flutter::EncodableValue>* codec_;
std::map<std::string, flutter::BinaryMessageHandler> handlers_;
};
} // namespace testing
#endif // PLATFORM_TESTS_TEST_PLUGIN_WINDOWS_TEST_UTILS_FAKE_HOST_MESSENGER_H_
| packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/fake_host_messenger.h/0 | {
"file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/utils/fake_host_messenger.h",
"repo_id": "packages",
"token_count": 670
} | 1,127 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:pigeon/ast.dart';
import 'package:pigeon/swift_generator.dart';
import 'package:test/test.dart';
import 'dart_generator_test.dart';
final Class emptyClass = Class(name: 'className', fields: <NamedType>[
NamedType(
name: 'namedTypeName',
type: const TypeDeclaration(baseName: 'baseName', isNullable: false),
)
]);
final Enum emptyEnum = Enum(
name: 'enumName',
members: <EnumMember>[EnumMember(name: 'enumMemberName')],
);
void main() {
test('gen one class', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Foobar'));
expect(code, contains('var field1: Int64? = nil'));
expect(code, contains('static func fromList(_ list: [Any?]) -> Foobar?'));
expect(code, contains('func toList() -> [Any?]'));
expect(code, isNot(contains('if (')));
});
test('gen one enum', () {
final Enum anEnum = Enum(
name: 'Foobar',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[],
enums: <Enum>[anEnum],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('enum Foobar: Int'));
expect(code, contains(' case one = 0'));
expect(code, contains(' case two = 1'));
expect(code, isNot(contains('if (')));
});
test('primitive enum host', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Bar', methods: <Method>[
Method(
name: 'bar',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: TypeDeclaration(
baseName: 'Foo',
associatedEnum: emptyEnum,
isNullable: false,
))
])
])
], classes: <Class>[], enums: <Enum>[
Enum(name: 'Foo', members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
])
]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('enum Foo: Int'));
expect(code, contains('let fooArg = Foo(rawValue: args[0] as! Int)!'));
expect(code, isNot(contains('if (')));
});
test('gen one host api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('protocol Api'));
expect(code, matches('func doSomething.*Input.*Output'));
expect(code, contains('doSomethingChannel.setMessageHandler'));
expect(code, isNot(contains('if (')));
});
test('all the simple datatypes header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'bool',
isNullable: true,
),
name: 'aBool'),
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'aInt'),
NamedType(
type: const TypeDeclaration(
baseName: 'double',
isNullable: true,
),
name: 'aDouble'),
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'aString'),
NamedType(
type: const TypeDeclaration(
baseName: 'Uint8List',
isNullable: true,
),
name: 'aUint8List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Int32List',
isNullable: true,
),
name: 'aInt32List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Int64List',
isNullable: true,
),
name: 'aInt64List'),
NamedType(
type: const TypeDeclaration(
baseName: 'Float64List',
isNullable: true,
),
name: 'aFloat64List'),
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('var aBool: Bool? = nil'));
expect(code, contains('var aInt: Int64? = nil'));
expect(code, contains('var aDouble: Double? = nil'));
expect(code, contains('var aString: String? = nil'));
expect(code, contains('var aUint8List: FlutterStandardTypedData? = nil'));
expect(code, contains('var aInt32List: FlutterStandardTypedData? = nil'));
expect(code, contains('var aInt64List: FlutterStandardTypedData? = nil'));
expect(code, contains('var aFloat64List: FlutterStandardTypedData? = nil'));
});
test('gen one flutter api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Api'));
expect(code, contains('init(binaryMessenger: FlutterBinaryMessenger)'));
expect(code, matches('func doSomething.*Input.*Output'));
expect(code, isNot(contains('if (')));
expect(code, isNot(matches(RegExp(r';$', multiLine: true))));
});
test('gen host void api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(matches('.*doSomething(.*) ->')));
expect(code, matches('doSomething(.*)'));
expect(code, isNot(contains('if (')));
});
test('gen flutter void return api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code,
contains('completion: @escaping (Result<Void, FlutterError>) -> Void'));
expect(code, contains('completion(.success(Void()))'));
expect(code, isNot(contains('if (')));
});
test('gen host void argument api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func doSomething() throws -> Output'));
expect(code, contains('let result = try api.doSomething()'));
expect(code, contains('reply(wrapResult(result))'));
expect(code, isNot(contains('if (')));
});
test('gen flutter void argument api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
)
])
], classes: <Class>[
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'func doSomething(completion: @escaping (Result<Output, FlutterError>) -> Void)'));
expect(code, contains('channel.sendMessage(nil'));
expect(code, isNot(contains('if (')));
});
test('gen list', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'List',
isNullable: true,
),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Foobar'));
expect(code, contains('var field1: [Any?]? = nil'));
expect(code, isNot(contains('if (')));
});
test('gen map', () {
final Root root = Root(apis: <Api>[], classes: <Class>[
Class(name: 'Foobar', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
),
name: 'field1')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Foobar'));
expect(code, contains('var field1: [AnyHashable: Any?]? = nil'));
expect(code, isNot(contains('if (')));
});
test('gen nested', () {
final Class classDefinition = Class(
name: 'Outer',
fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Nested',
associatedClass: emptyClass,
isNullable: true,
),
name: 'nested')
],
);
final Class nestedClass = Class(
name: 'Nested',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
name: 'data')
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition, nestedClass],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Outer'));
expect(code, contains('struct Nested'));
expect(code, contains('var nested: Nested? = nil'));
expect(code, contains('static func fromList(_ list: [Any?]) -> Outer?'));
expect(code, contains('nested = Nested.fromList(nestedList)'));
expect(code, contains('func toList() -> [Any?]'));
expect(code, isNot(contains('if (')));
// Single-element list serializations should not have a trailing comma.
expect(code, matches(RegExp(r'return \[\s*data\s*]')));
});
test('gen one async Host Api', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: 'arg')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
isAsynchronous: true,
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('protocol Api'));
expect(code, contains('api.doSomething(arg: argArg) { result in'));
expect(code, contains('reply(wrapResult(res))'));
expect(code, isNot(contains('if (')));
});
test('gen one async Flutter Api', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
isAsynchronous: true,
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('class Api'));
expect(code, matches('func doSomething.*Input.*completion.*Output.*Void'));
expect(code, isNot(contains('if (')));
});
test('gen one enum class', () {
final Enum anEnum = Enum(
name: 'Enum1',
members: <EnumMember>[
EnumMember(name: 'one'),
EnumMember(name: 'two'),
],
);
final Class classDefinition = Class(
name: 'EnumClass',
fields: <NamedType>[
NamedType(
type: TypeDeclaration(
baseName: 'Enum1',
associatedEnum: emptyEnum,
isNullable: true,
),
name: 'enum1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[anEnum],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('enum Enum1: Int'));
expect(code, contains('case one = 0'));
expect(code, contains('case two = 1'));
expect(code, isNot(contains('if (')));
});
test('header', () {
final Root root = Root(apis: <Api>[], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions(
copyrightHeader: <String>['hello world', ''],
);
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, startsWith('// hello world'));
// There should be no trailing whitespace on generated comments.
expect(code, isNot(matches(RegExp(r'^//.* $', multiLine: true))));
});
test('generics - list', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'List',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Foobar'));
expect(code, contains('var field1: [Int64?]'));
});
test('generics - maps', () {
final Class classDefinition = Class(
name: 'Foobar',
fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'String', isNullable: true),
]),
name: 'field1'),
],
);
final Root root = Root(
apis: <Api>[],
classes: <Class>[classDefinition],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('struct Foobar'));
expect(code, contains('var field1: [String?: String?]'));
});
test('host generics argument', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'arg')
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func doit(arg: [Int64?]'));
});
test('flutter generics argument', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
name: 'arg')
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func doit(arg argArg: [Int64?]'));
});
test('host generics return', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func doit() throws -> [Int64?]'));
expect(code, contains('let result = try api.doit()'));
expect(code, contains('reply(wrapResult(result))'));
});
test('flutter generics return', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration(
baseName: 'List',
isNullable: false,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'int', isNullable: true)
]),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'func doit(completion: @escaping (Result<[Int64?], FlutterError>) -> Void)'));
expect(code, contains('let result = listResponse[0] as! [Int64?]'));
expect(code, contains('completion(.success(result))'));
});
test('host multiple args', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'add',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
name: 'x',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
Parameter(
name: 'y',
type:
const TypeDeclaration(isNullable: false, baseName: 'int')),
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func add(x: Int64, y: Int64) throws -> Int64'));
expect(code, contains('let args = message as! [Any?]'));
expect(
code,
contains(
'let xArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32)'));
expect(
code,
contains(
'let yArg = args[1] is Int64 ? args[1] as! Int64 : Int64(args[1] as! Int32)'));
expect(code, contains('let result = try api.add(x: xArg, y: yArg)'));
expect(code, contains('reply(wrapResult(result))'));
});
test('flutter multiple args', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'add',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
name: 'x',
type:
const TypeDeclaration(baseName: 'int', isNullable: false)),
Parameter(
name: 'y',
type:
const TypeDeclaration(baseName: 'int', isNullable: false)),
],
returnType: const TypeDeclaration(baseName: 'int', isNullable: false),
)
])
], classes: <Class>[], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('let channel = FlutterBasicMessageChannel'));
expect(
code,
contains(
'let result = listResponse[0] is Int64 ? listResponse[0] as! Int64 : Int64(listResponse[0] as! Int32)'));
expect(code, contains('completion(.success(result))'));
expect(
code,
contains(
'func add(x xArg: Int64, y yArg: Int64, completion: @escaping (Result<Int64, FlutterError>) -> Void)'));
expect(code,
contains('channel.sendMessage([xArg, yArg] as [Any?]) { response in'));
});
test('return nullable host', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func doit() throws -> Int64?'));
});
test('return nullable host async', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
isAsynchronous: true,
parameters: <Parameter>[])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'func doit(completion: @escaping (Result<Int64?, Error>) -> Void'));
});
test('nullable argument host', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.host,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'let fooArg: Int64? = isNullish(args[0]) ? nil : (args[0] is Int64? ? args[0] as! Int64? : Int64(args[0] as! Int32))'));
});
test('nullable argument flutter', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doit',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'foo',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
)),
])
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'func doit(foo fooArg: Int64?, completion: @escaping (Result<Void, FlutterError>) -> Void)'));
});
test('nonnull fields', () {
final Root root = Root(apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: const TypeDeclaration.voidDeclaration(),
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
name: 'input')
]),
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('var input: String\n'));
});
test('transfers documentation comments', () {
final List<String> comments = <String>[
' api comment',
' api method comment',
' class comment',
' class field comment',
' enum comment',
' enum member comment',
];
int count = 0;
final List<String> unspacedComments = <String>['////////'];
int unspacedCount = 0;
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'api',
documentationComments: <String>[comments[count++]],
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
documentationComments: <String>[comments[count++]],
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[
Class(
name: 'class',
documentationComments: <String>[comments[count++]],
fields: <NamedType>[
NamedType(
documentationComments: <String>[comments[count++]],
type: const TypeDeclaration(
baseName: 'Map',
isNullable: true,
typeArguments: <TypeDeclaration>[
TypeDeclaration(baseName: 'String', isNullable: true),
TypeDeclaration(baseName: 'int', isNullable: true),
]),
name: 'field1',
),
],
),
],
enums: <Enum>[
Enum(
name: 'enum',
documentationComments: <String>[
comments[count++],
unspacedComments[unspacedCount++]
],
members: <EnumMember>[
EnumMember(
name: 'one',
documentationComments: <String>[comments[count++]],
),
EnumMember(name: 'two'),
],
),
],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
for (final String comment in comments) {
expect(code, contains('///$comment'));
}
expect(code, contains('/// ///'));
});
test("doesn't create codecs if no custom datatypes", () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, isNot(contains(': FlutterStandardReader ')));
});
test('creates custom codecs if custom datatypes present', () {
final Root root = Root(apis: <Api>[
AstFlutterApi(name: 'Api', methods: <Method>[
Method(
name: 'doSomething',
location: ApiLocation.flutter,
parameters: <Parameter>[
Parameter(
type: TypeDeclaration(
baseName: 'Input',
associatedClass: emptyClass,
isNullable: false,
),
name: '')
],
returnType: TypeDeclaration(
baseName: 'Output',
associatedClass: emptyClass,
isNullable: false,
),
isAsynchronous: true,
)
])
], classes: <Class>[
Class(name: 'Input', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'input')
]),
Class(name: 'Output', fields: <NamedType>[
NamedType(
type: const TypeDeclaration(
baseName: 'String',
isNullable: true,
),
name: 'output')
])
], enums: <Enum>[]);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains(': FlutterStandardReader '));
});
test('swift function signature', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'set',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'int',
isNullable: false,
),
name: 'value',
),
Parameter(
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
name: 'key',
),
],
swiftFunction: 'setValue(_:for:)',
returnType: const TypeDeclaration.voidDeclaration(),
)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func setValue(_ value: Int64, for key: String)'));
});
test('swift function signature with same name argument', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'set',
location: ApiLocation.host,
parameters: <Parameter>[
Parameter(
type: const TypeDeclaration(
baseName: 'String',
isNullable: false,
),
name: 'key',
),
],
swiftFunction: 'removeValue(key:)',
returnType: const TypeDeclaration.voidDeclaration(),
)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func removeValue(key: String)'));
});
test('swift function signature with no arguments', () {
final Root root = Root(
apis: <Api>[
AstHostApi(name: 'Api', methods: <Method>[
Method(
name: 'clear',
location: ApiLocation.host,
parameters: <Parameter>[],
swiftFunction: 'removeAll()',
returnType: const TypeDeclaration.voidDeclaration(),
)
])
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions swiftOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
swiftOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(code, contains('func removeAll()'));
});
test('connection error contains channel name', () {
final Root root = Root(
apis: <Api>[
AstFlutterApi(
name: 'Api',
methods: <Method>[
Method(
name: 'method',
location: ApiLocation.flutter,
returnType: const TypeDeclaration.voidDeclaration(),
parameters: <Parameter>[
Parameter(
name: 'field',
type: const TypeDeclaration(
baseName: 'int',
isNullable: true,
),
),
],
)
],
)
],
classes: <Class>[],
enums: <Enum>[],
);
final StringBuffer sink = StringBuffer();
const SwiftOptions kotlinOptions = SwiftOptions();
const SwiftGenerator generator = SwiftGenerator();
generator.generate(
kotlinOptions,
root,
sink,
dartPackageName: DEFAULT_PACKAGE_NAME,
);
final String code = sink.toString();
expect(
code,
contains(
'completion(.failure(createConnectionError(withChannelName: channelName)))'));
expect(
code,
contains(
'return FlutterError(code: "channel-error", message: "Unable to establish connection on channel: \'\\(channelName)\'.", details: "")'));
});
}
| packages/packages/pigeon/test/swift_generator_test.dart/0 | {
"file_path": "packages/packages/pigeon/test/swift_generator_test.dart",
"repo_id": "packages",
"token_count": 22759
} | 1,128 |
test_on: vm
| packages/packages/platform/dart_test.yaml/0 | {
"file_path": "packages/packages/platform/dart_test.yaml",
"repo_id": "packages",
"token_count": 6
} | 1,129 |
// 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
/// A simple factory that creates a dummy platform view for testing.
public class DummyPlatformViewFactory: NSObject, FlutterPlatformViewFactory {
private var messenger: FlutterBinaryMessenger
init(messenger: FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
public func create(
withFrame frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?
) -> FlutterPlatformView {
return DummyPlatformView(
frame: frame,
viewIdentifier: viewId,
arguments: args,
binaryMessenger: messenger)
}
public func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
/// A native view that will remove it's tag if clicked.
public class CustomView: UIView {
var timesClicked = 0
var nativeLabel = UILabel()
override public func hitTest(
_ point: CGPoint,
with event: UIEvent?
) -> UIView? {
if viewWithTag(1) != nil {
viewWithTag(1)?.removeFromSuperview()
createNativeView(view: self)
}
timesClicked += 1
nativeLabel.text = "Traversed \(timesClicked) subviews"
return super.hitTest(point, with: event)
}
func createNativeView(view _view: CustomView) {
nativeLabel.text = "Traversed \(timesClicked) subviews"
nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)
_view.addSubview(nativeLabel)
}
}
/// A flutter platform view that displays a simple native view.
class DummyPlatformView: NSObject, FlutterPlatformView {
private var _view: CustomView
init(
frame: CGRect,
viewIdentifier viewId: Int64,
arguments args: Any?,
binaryMessenger messenger: FlutterBinaryMessenger?
) {
_view = CustomView()
super.init()
createNativeView(view: _view)
}
func view() -> UIView {
return _view
}
func createNativeView(view _view: CustomView) {
let nativeLabel = UILabel()
nativeLabel.tag = 1
nativeLabel.text = "Native View Not Clicked"
nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)
_view.addSubview(nativeLabel)
}
}
| packages/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner/DummyPlatformViewFactory.swift/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner/DummyPlatformViewFactory.swift",
"repo_id": "packages",
"token_count": 797
} | 1,130 |
name: pointer_interceptor
description: A widget to prevent clicks from being swallowed by underlying HtmlElementViews on the web.
repository: https://github.com/flutter/packages/tree/main/packages/pointer_interceptor/pointer_interceptor
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+pointer_interceptor%22
version: 0.10.1
environment:
sdk: ">=3.1.0 <4.0.0"
flutter: ">=3.13.0"
flutter:
plugin:
implements: pointer_interceptor_platform_interface
platforms:
web:
default_package: pointer_interceptor_web
ios:
default_package: pointer_interceptor_ios
dependencies:
flutter:
sdk: flutter
flutter_web_plugins:
sdk: flutter
pointer_interceptor_ios: ^0.10.0
pointer_interceptor_platform_interface: ^0.10.0
pointer_interceptor_web: ^0.10.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- web
- widgets
- pointer-interceptor
| packages/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml",
"repo_id": "packages",
"token_count": 366
} | 1,131 |
name: pointer_interceptor_ios
description: iOS implementation of the pointer_interceptor plugin.
repository: https://github.com/flutter/packages/tree/main/packages/pointer_interceptor/pointer_interceptor_ios
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3Apointer_interceptor
version: 0.10.0+2
environment:
sdk: ^3.2.3
flutter: ">=3.16.6"
flutter:
plugin:
implements: pointer_interceptor
platforms:
ios:
pluginClass: PointerInterceptorIosPlugin
dartPluginClass: PointerInterceptorIOS
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.1.7
pointer_interceptor_platform_interface: ^0.10.0
dev_dependencies:
flutter_test:
sdk: flutter
topics:
- pointer-interceptor
- ios
| packages/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml/0 | {
"file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/pubspec.yaml",
"repo_id": "packages",
"token_count": 296
} | 1,132 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
## 5.0.2
* Removes mention of the removed record/replay feature from README.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
* Fixes new lint warnings.
## 5.0.1
* Transfers the package source from https://github.com/google/process.dart to
https://github.com/flutter/packages.
## 5.0.0
* Remove the `covariant` keyword from `stderrEncoding` and `stdoutEncoding`
parameters.
* Update dependencies to work on Dart 3.
* Bumped min SDK dependency to nearest non-prerelease version (2.14.0)
## 4.2.4
* Mark `stderrEncoding` and `stdoutEncoding` parameters as nullable again,
now that the upstream SDK issue has been fixed.
## 4.2.3
* Rollback to version 4.2.1 (https://github.com/google/process.dart/issues/64)
## 4.2.2
* Mark `stderrEncoding` and `stdoutEncoding` parameters as nullable.
## 4.2.1
* Added custom exception types `ProcessPackageException` and
`ProcessPackageExecutableNotFoundException` to provide extra
information from exception conditions.
## 4.2.0
* Fix the signature of `ProcessManager.canRun` to be consistent with
`LocalProcessManager`.
## 4.1.1
* Fixed `getExecutablePath()` to only return path items that are
executable and readable to the user.
## 4.1.0
* Fix the signatures of `ProcessManager.run`, `.runSync`, and `.start` to be
consistent with `LocalProcessManager`'s.
* Added more details to the `ArgumentError` thrown when a command cannot be resolved
to an executable.
## 4.0.0
* First stable null safe release.
## 4.0.0-nullsafety.4
* Update supported SDK range.
## 4.0.0-nullsafety.3
* Update supported SDK range.
## 4.0.0-nullsafety.2
* Update supported SDK range.
## 4.0.0-nullsafety.1
* Migrate to null-safety.
* Remove record/replay functionality.
* Remove implicit casts in preparation for null-safety.
* Remove dependency on `package:intl` and `package:meta`.
## 3.0.13
* Handle `currentDirectory` throwing an exception in `getExecutablePath()`.
## 3.0.12
* Updated version constraint on intl.
## 3.0.11
* Fix bug: don't add quotes if the file name already has quotes.
## 3.0.10
* Added quoted strings to indicate where the command name ends and the arguments
begin otherwise, the file name is ambiguous on Windows.
## 3.0.9
* Fixed bug in `ProcessWrapper`
## 3.0.8
* Fixed bug in `ProcessWrapper`
## 3.0.7
* Renamed `Process` to `ProcessWrapper`
## 3.0.6
* Added class `Process`, a simple wrapper around dart:io's `Process` class.
## 3.0.5
* Fixes for missing_return analysis errors with 2.10.0-dev.1.0.
## 3.0.4
* Fix unit tests
* Update SDK constraint to 3.
## 3.0.3
* Update dependency on `package:file`
## 3.0.2
* Remove upper case constants.
* Update SDK constraint to 2.0.0-dev.54.0.
* Fix tests for Dart 2.
## 3.0.1
* General cleanup
## 3.0.0
* Cleanup getExecutablePath() to better respect the platform
## 2.0.9
* Bumped `package:file` dependency
### 2.0.8
* Fixed method getArguments to qualify the map method with the specific
String type
### 2.0.7
* Remove `set exitCode` instances
### 2.0.6
* Fix SDK constraint.
* rename .analysis_options file to analaysis_options.yaml.
* Use covariant in place of @checked.
* Update comment style generics.
### 2.0.5
* Bumped maximum Dart SDK version to 2.0.0-dev.infinity
### 2.0.4
* relax dependency requirement for `intl`
### 2.0.3
* relax dependency requirement for `platform`
## 2.0.2
* Fix a strong mode function expression return type inference bug with Dart
1.23.0-dev.10.0.
## 2.0.1
* Fixed bug in `ReplayProcessManager` whereby it could try to write to `stdout`
or `stderr` after the streams were closed.
## 2.0.0
* Bumped `package:file` dependency to 2.0.1
## 1.1.0
* Added support to transparently find the right executable under Windows.
## 1.0.1
* The `executable` and `arguments` parameters have been merged into one
`command` parameter in the `run`, `runSync`, and `start` methods of
`ProcessManager`.
* Added support for sanitization of command elements in
`RecordingProcessManager` and `ReplayProcessManager` via the `CommandElement`
class.
## 1.0.0
* Initial version
| packages/packages/process/CHANGELOG.md/0 | {
"file_path": "packages/packages/process/CHANGELOG.md",
"repo_id": "packages",
"token_count": 1388
} | 1,133 |
## NEXT
* Updates minimum supported SDK version to Flutter 3.13/Dart 3.1.
* Updates compileSdk version to 34.
## 1.0.10
* Updates minimum required plugin_platform_interface version to 2.1.7.
* Updates minimum supported SDK version to Flutter 3.10/Dart 3.0.
## 1.0.9
* Changes method channels to pigeon.
## 1.0.8
* Adds pub topics to package metadata.
* Updates minimum supported SDK version to Flutter 3.7/Dart 2.19.
## 1.0.7
* Adjusts SDK checks for better testability.
## 1.0.6
* Removes obsolete null checks on non-nullable values.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.
## 1.0.5
* Fixes Java warnings.
## 1.0.4
* Fixes compatibility with AGP versions older than 4.2.
## 1.0.3
* Adds a namespace for compatibility with AGP 8.0.
## 1.0.2
* Clarifies explanation of endorsement in README.
* Aligns Dart and Flutter SDK constraints.
* Updates compileSdkVersion to 33.
## 1.0.1
* Updates links for the merge of flutter/plugins into flutter/packages.
* Updates minimum Flutter version to 3.0.
## 1.0.0
* Updates version to 1.0 to reflect current status.
* Updates minimum Flutter version to 2.10.
* Updates mockito-core to 4.6.1.
* Removes deprecated FieldSetter from QuickActionsTest.
## 0.6.2
* Updates gradle version to 7.2.1.
## 0.6.1
* Allows Android to trigger quick actions without restarting the app.
## 0.6.0+11
* Updates references to the obsolete master branch.
## 0.6.0+10
* Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors
lint warnings.
## 0.6.0+9
* Switches to a package-internal implementation of the platform interface.
| packages/packages/quick_actions/quick_actions_android/CHANGELOG.md/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/CHANGELOG.md",
"repo_id": "packages",
"token_count": 545
} | 1,134 |
// 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.quickactionsexample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.util.Log;
import androidx.lifecycle.Lifecycle;
import androidx.test.core.app.ActivityScenario;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.Until;
import io.flutter.plugins.quickactions.QuickActionsPlugin;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class QuickActionsTest {
private Context context;
private UiDevice device;
private ActivityScenario<QuickActionsTestActivity> scenario;
@Before
public void setUp() {
context = ApplicationProvider.getApplicationContext();
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
scenario = ensureAppRunToView();
ensureAllAppShortcutsAreCreated();
}
@After
public void tearDown() {
scenario.close();
Log.i(QuickActionsTest.class.getSimpleName(), "Run to completion");
}
@Test
public void quickActionPluginIsAdded() {
final ActivityScenario<QuickActionsTestActivity> scenario =
ActivityScenario.launch(QuickActionsTestActivity.class);
scenario.onActivity(
activity -> {
assertTrue(activity.engine.getPlugins().has(QuickActionsPlugin.class));
});
}
@Test
public void appShortcutsAreCreated() {
List<ShortcutInfo> expectedShortcuts = createMockShortcuts();
ShortcutManager shortcutManager =
(ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
List<ShortcutInfo> dynamicShortcuts = shortcutManager.getDynamicShortcuts();
// Assert the app shortcuts defined in ../lib/main.dart.
assertFalse(dynamicShortcuts.isEmpty());
assertEquals(expectedShortcuts.size(), dynamicShortcuts.size());
for (ShortcutInfo expectedShortcut : expectedShortcuts) {
ShortcutInfo dynamicShortcut =
dynamicShortcuts
.stream()
.filter(s -> s.getId().equals(expectedShortcut.getId()))
.findFirst()
.get();
assertEquals(expectedShortcut.getShortLabel(), dynamicShortcut.getShortLabel());
assertEquals(expectedShortcut.getLongLabel(), dynamicShortcut.getLongLabel());
}
}
@Test
public void appShortcutLaunchActivityAfterStarting() {
// Arrange
List<ShortcutInfo> shortcuts = createMockShortcuts();
ShortcutInfo firstShortcut = shortcuts.get(0);
ShortcutManager shortcutManager =
(ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
List<ShortcutInfo> dynamicShortcuts = shortcutManager.getDynamicShortcuts();
ShortcutInfo dynamicShortcut =
dynamicShortcuts
.stream()
.filter(s -> s.getId().equals(firstShortcut.getId()))
.findFirst()
.get();
Intent dynamicShortcutIntent = dynamicShortcut.getIntent();
AtomicReference<QuickActionsTestActivity> initialActivity = new AtomicReference<>();
scenario.onActivity(initialActivity::set);
clearAnySystemDialog(context);
String appReadySentinel = " has launched";
// Act
context.startActivity(dynamicShortcutIntent);
device.wait(Until.hasObject(By.descContains(appReadySentinel)), 2000);
AtomicReference<QuickActionsTestActivity> currentActivity = new AtomicReference<>();
scenario.onActivity(currentActivity::set);
// Assert
Assert.assertTrue(
"AppShortcut:" + firstShortcut.getId() + " does not launch the correct activity",
// We can only find the shortcut type in content description while inspecting it in Ui
// Automator Viewer.
device.hasObject(By.descContains(firstShortcut.getId() + appReadySentinel)));
// This is Android SingleTop behavior in which Android does not destroy the initial activity and
// launch a new activity.
Assert.assertEquals(initialActivity.get(), currentActivity.get());
}
private void ensureAllAppShortcutsAreCreated() {
device.wait(Until.hasObject(By.text("actions ready")), 1000);
}
private List<ShortcutInfo> createMockShortcuts() {
List<ShortcutInfo> expectedShortcuts = new ArrayList<>();
String actionOneLocalizedTitle = "Action one";
expectedShortcuts.add(
new ShortcutInfo.Builder(context, "action_one")
.setShortLabel(actionOneLocalizedTitle)
.setLongLabel(actionOneLocalizedTitle)
.build());
String actionTwoLocalizedTitle = "Action two";
expectedShortcuts.add(
new ShortcutInfo.Builder(context, "action_two")
.setShortLabel(actionTwoLocalizedTitle)
.setLongLabel(actionTwoLocalizedTitle)
.build());
return expectedShortcuts;
}
private ActivityScenario<QuickActionsTestActivity> ensureAppRunToView() {
final ActivityScenario<QuickActionsTestActivity> scenario =
ActivityScenario.launch(QuickActionsTestActivity.class);
scenario.moveToState(Lifecycle.State.STARTED);
return scenario;
}
// Broadcast a request to clear any system dialog that blocks the application from obtaining
// focus. See https://github.com/flutter/flutter/issues/140987
private void clearAnySystemDialog(Context context) {
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
}
| packages/packages/quick_actions/quick_actions_android/example/android/app/src/androidTest/java/io/flutter/plugins/quickactionsexample/QuickActionsTest.java/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/example/android/app/src/androidTest/java/io/flutter/plugins/quickactionsexample/QuickActionsTest.java",
"repo_id": "packages",
"token_count": 2041
} | 1,135 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'package:flutter/material.dart';
import 'package:quick_actions_android/quick_actions_android.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Quick Actions Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String shortcut = 'no action set';
@override
void initState() {
super.initState();
final QuickActionsAndroid quickActions = QuickActionsAndroid();
quickActions.initialize((String shortcutType) {
setState(() {
shortcut = '$shortcutType has launched';
});
});
quickActions.setShortcutItems(<ShortcutItem>[
const ShortcutItem(
type: 'action_one',
localizedTitle: 'Action one',
icon: 'AppIcon',
),
const ShortcutItem(
type: 'action_two',
localizedTitle: 'Action two',
icon: 'ic_launcher'),
]).then((void _) {
setState(() {
if (shortcut == 'no action set') {
shortcut = 'actions ready';
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(shortcut),
),
body: const Center(
child: Text('On home screen, long press the app icon to '
'get Action one or Action two options. Tapping on that action should '
'set the toolbar title.'),
),
);
}
}
| packages/packages/quick_actions/quick_actions_android/example/lib/main.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_android/example/lib/main.dart",
"repo_id": "packages",
"token_count": 776
} | 1,136 |
// 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:quick_actions_ios/messages.g.dart';
import 'package:quick_actions_ios/quick_actions_ios.dart';
import 'package:quick_actions_platform_interface/quick_actions_platform_interface.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final _FakeQuickActionsApi api = _FakeQuickActionsApi();
final QuickActionsIos quickActions = QuickActionsIos(api: api);
test('registerWith() registers correct instance', () {
QuickActionsIos.registerWith();
expect(QuickActionsPlatform.instance, isA<QuickActionsIos>());
});
group('#initialize', () {
test('initialize', () {
expect(quickActions.initialize((_) {}), completes);
});
});
test('setShortcutItems', () async {
await quickActions.initialize((String type) {});
const ShortcutItem item =
ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg');
await quickActions.setShortcutItems(<ShortcutItem>[item]);
expect(api.items.first.type, item.type);
expect(api.items.first.localizedTitle, item.localizedTitle);
expect(api.items.first.icon, item.icon);
});
test('clearShortCutItems', () {
quickActions.initialize((String type) {});
const ShortcutItem item =
ShortcutItem(type: 'test', localizedTitle: 'title', icon: 'icon.svg');
quickActions.setShortcutItems(<ShortcutItem>[item]);
quickActions.clearShortcutItems();
expect(api.items.isEmpty, true);
});
test('Shortcut item can be constructed', () {
const String type = 'type';
const String localizedTitle = 'title';
const String icon = 'foo';
const ShortcutItem item =
ShortcutItem(type: type, localizedTitle: localizedTitle, icon: icon);
expect(item.type, type);
expect(item.localizedTitle, localizedTitle);
expect(item.icon, icon);
});
}
class _FakeQuickActionsApi implements IOSQuickActionsApi {
List<ShortcutItem> items = <ShortcutItem>[];
bool getLaunchActionCalled = false;
@override
Future<void> clearShortcutItems() async {
items = <ShortcutItem>[];
return;
}
@override
Future<void> setShortcutItems(List<ShortcutItemMessage?> itemsList) async {
await clearShortcutItems();
for (final ShortcutItemMessage? element in itemsList) {
items.add(shortcutItemMessageToShortcutItem(element!));
}
}
}
/// Conversion tool to change [ShortcutItemMessage] back to [ShortcutItem]
ShortcutItem shortcutItemMessageToShortcutItem(ShortcutItemMessage item) {
return ShortcutItem(
type: item.type,
localizedTitle: item.localizedTitle,
icon: item.icon,
);
}
| packages/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart/0 | {
"file_path": "packages/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart",
"repo_id": "packages",
"token_count": 944
} | 1,137 |
#include "Generated.xcconfig"
| packages/packages/rfw/example/hello/ios/Flutter/Release.xcconfig/0 | {
"file_path": "packages/packages/rfw/example/hello/ios/Flutter/Release.xcconfig",
"repo_id": "packages",
"token_count": 12
} | 1,138 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.