Merge master

This commit is contained in:
Mouad Debbar 2025-10-01 12:16:14 -04:00
commit 7bb8b978f0
105 changed files with 1983 additions and 323 deletions

View File

@ -2274,7 +2274,7 @@ targets:
- name: Linux web_tool_tests
recipe: flutter/flutter_drone
timeout: 90 # https://github.com/flutter/flutter/issues/169634
timeout: 60
properties:
dependencies: >-
[
@ -2287,7 +2287,7 @@ targets:
subshard: "1_1"
tags: >
["framework", "hostonly", "shard", "linux"]
test_timeout_secs: "5400" # https://github.com/flutter/flutter/issues/162714
test_timeout_secs: "3600" # 60 minutes to match the global `timeout` property.
runIf:
- dev/**
- packages/flutter_tools/**
@ -6686,6 +6686,7 @@ targets:
subshard: "2_2"
tags: >
["framework", "hostonly", "shard"]
test_timeout_secs: "3600" # 60 minutes to match the global `timeout` property.
runIf:
- dev/**
- packages/flutter_tools/**

14
DEPS
View File

@ -14,7 +14,7 @@ vars = {
'flutter_git': 'https://flutter.googlesource.com',
'skia_git': 'https://skia.googlesource.com',
'llvm_git': 'https://llvm.googlesource.com',
'skia_revision': 'bb3b6bd4be0dd757165a5723e1794f7ad2211d49',
'skia_revision': 'c44a36470d077020b978f87fc5720f85dfc68d5b',
# WARNING: DO NOT EDIT canvaskit_cipd_instance MANUALLY
# See `lib/web_ui/README.md` for how to roll CanvasKit to a new version.
@ -56,7 +56,7 @@ vars = {
# Dart is: https://github.com/dart-lang/sdk/blob/main/DEPS
# You can use //tools/dart/create_updated_flutter_deps.py to produce
# updated revision list of existing dependencies.
'dart_revision': 'af31d2637b6bced76edd4bcead0d941fe9ad871a',
'dart_revision': '8ffec1435cf31802e237765d6e9aae48fe5bd19e',
# WARNING: DO NOT EDIT MANUALLY
# The lines between blank lines above and below are generated by a script. See create_updated_flutter_deps.py
@ -71,10 +71,10 @@ vars = {
'dart_libprotobuf_rev': '24487dd1045c7f3d64a21f38a3f0c06cc4cf2edb',
'dart_perfetto_rev': '13ce0c9e13b0940d2476cd0cff2301708a9a2e2b',
'dart_protobuf_gn_rev': 'ca669f79945418f6229e4fef89b666b2a88cbb10',
'dart_protobuf_rev': '07eed6e8cc0535189112ae8373aa8f16f4a5c3ca',
'dart_pub_rev': '469eb6193c0a49495ea2ce7432cf749f077ad596',
'dart_protobuf_rev': '14bbd0bd7ff9b7e322ff4e85bd243f6905170b92',
'dart_pub_rev': 'f7f1891e2de3d795532f45ec214f88ac912ffcd6',
'dart_sync_http_rev': '6666fff944221891182e1f80bf56569338164d72',
'dart_tools_rev': 'ecd7dd523c8a5761f337eedce8878b092996a75c',
'dart_tools_rev': '2ef298e48450de9d2443d466ec4d61172a71b113',
'dart_vector_math_rev': '3939545edc38ed657381381d33acde02c49ff827',
'dart_web_rev': '0baaea4de4dfd60db85dd112d8cc7480d0dd8bd8',
'dart_webdev_rev': '23aefebea46c1f94c27703743b2c8db1f651bf29',
@ -368,7 +368,7 @@ deps = {
Var('dart_git') + '/external/github.com/google/webkit_inspection_protocol.dart.git' + '@' + Var('dart_webkit_inspection_protocol_rev'),
'engine/src/flutter/third_party/dart/tools/sdks/dart-sdk':
{'dep_type': 'cipd', 'packages': [{'package': 'dart/dart-sdk/${{platform}}', 'version': 'git_revision:0bf5d0bb49d7872a1a01e55dbea63ad7455d754e'}]},
{'dep_type': 'cipd', 'packages': [{'package': 'dart/dart-sdk/${{platform}}', 'version': 'git_revision:782552bdddc112c62db28ec7e9b2763f4457a3ea'}]},
# WARNING: end of dart dependencies list that is cleaned up automatically - see create_updated_flutter_deps.py.
@ -807,7 +807,7 @@ deps = {
'packages': [
{
'package': 'fuchsia/sdk/core/linux-amd64',
'version': 'rcOl0yxJb4znJ903YZ0BtnELs13r0WQ7TACeefPZ3bgC'
'version': '1Ai6VL4vb_GdGnWhg0uhlZW3yT8DJinUL0G7BZ_yGcIC'
}
],
'condition': 'download_fuchsia_deps and not download_fuchsia_sdk',

View File

@ -1 +1 @@
34eec7850cce13f0b60f041ca6cea1206abd957e
287739d0accebbcd6459dfa86f559916db793318

View File

@ -213,11 +213,14 @@ Future<void> _installPlugins({
await eval(
'pod',
<String>['install'],
environment: <String, String>{'LANG': 'en_US.UTF-8'},
<String>['install', '--verbose'],
environment: <String, String>{
// See https://github.com/flutter/flutter/issues/10873.
// CocoaPods analytics adds a lot of latency.
'COCOAPODS_DISABLE_STATS': 'true',
'LANG': 'en_US.UTF-8',
},
workingDirectory: xcodeProjectDir.path,
printStdout: false,
printStderr: false,
);
}

View File

@ -328,7 +328,7 @@
},
{
"dependency": "firefox",
"version": "version:132.0"
"version": "version:143.0"
}
],
"tasks": [

View File

@ -101,6 +101,7 @@ typedef CanvasPath Path;
V(PlatformConfigurationNativeApi::EndWarmUpFrame) \
V(PlatformConfigurationNativeApi::Render) \
V(PlatformConfigurationNativeApi::UpdateSemantics) \
V(PlatformConfigurationNativeApi::SetApplicationLocale) \
V(PlatformConfigurationNativeApi::SetNeedsReportTimings) \
V(PlatformConfigurationNativeApi::SetIsolateDebugName) \
V(PlatformConfigurationNativeApi::SetSemanticsTreeEnabled) \

View File

@ -976,6 +976,15 @@ class PlatformDispatcher {
/// list has not been set or is empty.
Locale get locale => locales.isEmpty ? const Locale.fromSubtags() : locales.first;
/// Sets the locale for the application in engine.
///
/// This is typically called by framework to set the locale based on which
/// locale the Flutter app actually uses.
void setApplicationLocale(Locale locale) => _setApplicationLocale(locale.toLanguageTag());
@Native<Void Function(Handle)>(symbol: 'PlatformConfigurationNativeApi::SetApplicationLocale')
external static void _setApplicationLocale(String locale);
/// The full system-reported supported locales of the device.
///
/// This establishes the language and formatting conventions that application

View File

@ -168,6 +168,7 @@ struct SemanticsNode {
std::string linkUrl;
SemanticsRole role;
SemanticsValidationResult validationResult = SemanticsValidationResult::kNone;
// A locale string in BCP 47 format
std::string locale;
};

View File

@ -677,6 +677,14 @@ void PlatformConfigurationNativeApi::UpdateSemantics(int64_t view_id,
view_id, update);
}
void PlatformConfigurationNativeApi::SetApplicationLocale(std::string locale) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()
->platform_configuration()
->client()
->SetApplicationLocale(std::move(locale));
}
void PlatformConfigurationNativeApi::SetSemanticsTreeEnabled(bool enabled) {
UIDartState::ThrowIfUIOperationsProhibited();
UIDartState::Current()

View File

@ -98,6 +98,13 @@ class PlatformConfigurationClient {
///
virtual void UpdateSemantics(int64_t viewId, SemanticsUpdate* update) = 0;
//--------------------------------------------------------------------------
/// @brief Framework sets the application locale
///
/// @param[in] locale The application locale in BCP 47 format.
///
virtual void SetApplicationLocale(std::string locale) = 0;
//--------------------------------------------------------------------------
/// @brief Notifies whether Framework starts generating semantics tree.
///
@ -633,6 +640,8 @@ class PlatformConfigurationNativeApi {
static void UpdateSemantics(int64_t viewId, SemanticsUpdate* update);
static void SetApplicationLocale(std::string locale);
static void SetSemanticsTreeEnabled(bool enabled);
static void SetNeedsReportTimings(bool value);

View File

@ -195,20 +195,17 @@ If you have questions, contact the Flutter Web team on Flutter Discord on the
We test with Firefox on LUCI in the Linux Web Engine builder. The process for
rolling Firefox is even easier than Chromium. Simply update `package_lock.yaml`
with the latest version of Firefox, and run `package_roller.dart`.
with the latest version of Firefox, and run:
```
dart dev/package_roller.dart
```
#### .ci.yaml
After rolling Chrome and/or Firefox, also update the CI dependencies in
`.ci.yaml` to make use of the new versions. The lines look like
After rolling Chrome and/or Firefox, also update the CI dependencies by running:
```yaml
dependencies: >-
[
{"dependency": "chrome_and_driver", "version": "version:107.0"},
{"dependency": "firefox", "version": "version:83.0"},
{"dependency": "goldctl", "version": "git_revision:720a542f6fe4f92922c3b8f0fdcc4d2ac6bb83cd"}
]
```
felt generate-builder-json
```
##### **package_roller.dart**

View File

@ -75,7 +75,7 @@ class WindowsPlatformBinding extends PlatformBinding {
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/win64/en-US/'
'https://ftp.mozilla.org/pub/firefox/releases/$version/win64/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override
@ -109,11 +109,11 @@ class LinuxPlatformBinding extends PlatformBinding {
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/linux-x86_64/en-US/'
'https://ftp.mozilla.org/pub/firefox/releases/$version/linux-x86_64/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override
String getFirefoxDownloadFilename(String version) => 'firefox-$version.tar.bz2';
String getFirefoxDownloadFilename(String version) => 'firefox-$version.tar.xz';
@override
String getFirefoxExecutablePath(io.Directory versionDir) =>
@ -145,7 +145,7 @@ abstract class MacPlatformBinding extends PlatformBinding {
@override
String getFirefoxDownloadUrl(String version) =>
'https://download-installer.cdn.mozilla.net/pub/firefox/releases/$version/mac/en-US/'
'https://ftp.mozilla.org/pub/firefox/releases/$version/mac/en-US/'
'${getFirefoxDownloadFilename(version)}';
@override

View File

@ -4,7 +4,7 @@ chrome:
version: '133.0.6943.53'
firefox:
version: '132.0'
version: '143.0'
edge:
launcher_version: '1.2.0.0'

View File

@ -87,6 +87,8 @@ abstract class PlatformDispatcher {
void setSemanticsTreeEnabled(bool enabled) {}
void setApplicationLocale(Locale locale) {}
AccessibilityFeatures get accessibilityFeatures;
VoidCallback? get onAccessibilityFeaturesChanged;

View File

@ -353,13 +353,28 @@ class SemanticTextField extends SemanticRole {
if (semanticsObject.flags.isObscured) {
input.type = 'password';
} else {
input.type = switch (semanticsObject.inputType) {
ui.SemanticsInputType.search => 'search',
ui.SemanticsInputType.email => 'email',
ui.SemanticsInputType.url => 'url',
ui.SemanticsInputType.phone => 'tel',
_ => 'text',
};
// For email inputs, prefer type="text" with inputmode="email" so that
// browsers keep selection APIs enabled while still providing email
// keyboards and hints. This avoids InvalidStateError and enables
// proper selection/cursor operations.
input.removeAttribute('inputmode');
input.removeAttribute('autocapitalize');
input.autocomplete = 'off';
input.type = 'text';
switch (semanticsObject.inputType) {
case ui.SemanticsInputType.search:
input.type = 'search';
case ui.SemanticsInputType.url:
input.type = 'url';
case ui.SemanticsInputType.phone:
input.type = 'tel';
case ui.SemanticsInputType.email:
input.setAttribute('inputmode', 'email');
input.setAttribute('autocapitalize', 'none');
input.autocomplete = 'email';
default:
}
}
}

View File

@ -124,7 +124,8 @@ void testMain() {
ui.SemanticsInputType.url: 'url',
ui.SemanticsInputType.phone: 'tel',
ui.SemanticsInputType.search: 'search',
ui.SemanticsInputType.email: 'email',
// Email uses type="text" to preserve selection APIs under semantics.
ui.SemanticsInputType.email: 'text',
};
for (final ui.SemanticsInputType type in ui.SemanticsInputType.values) {
createTextFieldSemantics(value: 'text', inputType: type);
@ -133,6 +134,19 @@ void testMain() {
}
});
test('email input uses type=text with inputmode=email and autocomplete=email', () {
createTextFieldSemantics(value: 'text', inputType: ui.SemanticsInputType.email);
final node = owner().debugSemanticsTree![0]!;
final textFieldRole = node.semanticRole! as SemanticTextField;
final inputElement = textFieldRole.editableElement as DomHTMLInputElement;
expect(inputElement.type, 'text');
expect(inputElement.getAttribute('inputmode'), 'email');
expect(inputElement.getAttribute('autocapitalize'), 'none');
expect(inputElement.autocomplete, 'email');
});
test('renders a disabled text field', () {
createTextFieldSemantics(isEnabled: false, value: 'hello');
expectSemanticsTree(owner(), '''<sem><input /></sem>''');

View File

@ -712,6 +712,7 @@ class FakePlatformConfigurationClient : public PlatformConfigurationClient {
double width,
double height) override {}
void UpdateSemantics(int64_t view_id, SemanticsUpdate* update) override {}
void SetApplicationLocale(std::string locale) override {}
void SetSemanticsTreeEnabled(bool enabled) override {}
void HandlePlatformMessage(
std::unique_ptr<PlatformMessage> message) override {}

View File

@ -444,6 +444,11 @@ void RuntimeController::UpdateSemantics(int64_t view_id,
client_.UpdateSemantics(view_id, update->takeNodes(), update->takeActions());
}
// |PlatformConfigurationClient|
void RuntimeController::SetApplicationLocale(std::string locale) {
client_.SetApplicationLocale(std::move(locale));
}
// |PlatformConfigurationClient|
void RuntimeController::SetSemanticsTreeEnabled(bool enabled) {
client_.SetSemanticsTreeEnabled(enabled);

View File

@ -636,6 +636,9 @@ class RuntimeController : public PlatformConfigurationClient,
// |PlatformConfigurationClient|
void UpdateSemantics(int64_t view_id, SemanticsUpdate* update) override;
// |PlatformConfigurationClient|
void SetApplicationLocale(std::string locale) override;
// |PlatformConfigurationClient|
void SetSemanticsTreeEnabled(bool enabled) override;

View File

@ -19,6 +19,7 @@ class MockRuntimeDelegate : public RuntimeDelegate {
std::vector<SemanticsNodeUpdates> updates;
std::vector<CustomAccessibilityActionUpdates> actions;
std::string DefaultRouteName() override { return ""; }
std::string locale;
void ScheduleFrame(bool regenerate_layer_trees = true) override {}
@ -35,6 +36,10 @@ class MockRuntimeDelegate : public RuntimeDelegate {
this->actions.push_back(actions);
}
void SetApplicationLocale(std::string locale) override {
this->locale = std::move(locale);
}
void SetSemanticsTreeEnabled(bool enabled) override {}
void HandlePlatformMessage(
@ -96,6 +101,12 @@ class RuntimeControllerTester {
ASSERT_FALSE(delegate_.actions.empty());
}
void CanUpdateSetApplicationLocale() {
ASSERT_TRUE(delegate_.locale.empty());
runtime_controller_.SetApplicationLocale("es-MX");
ASSERT_TRUE(delegate_.locale == "es-MX");
}
private:
MockRuntimeDelegate delegate_;
UIDartState::Context& context_;
@ -146,4 +157,16 @@ TEST_F(RuntimeControllerTest, CanUpdateSemanticsWhenSetSemanticsTreeEnabled) {
DestroyShell(std::move(shell), task_runners);
}
TEST_F(RuntimeControllerTest, CanSetApplicationLocale) {
TaskRunners task_runners("test", // label
GetCurrentTaskRunner(), // platform
CreateNewThread(), // raster
CreateNewThread(), // ui
CreateNewThread() // io
);
UIDartState::Context context(task_runners);
auto tester = std::make_shared<RuntimeControllerTester>(context);
tester->CanUpdateSetApplicationLocale();
}
} // namespace flutter::testing

View File

@ -36,6 +36,8 @@ class RuntimeDelegate {
SemanticsNodeUpdates update,
CustomAccessibilityActionUpdates actions) = 0;
virtual void SetApplicationLocale(std::string locale) = 0;
virtual void SetSemanticsTreeEnabled(bool enabled) = 0;
virtual void HandlePlatformMessage(

View File

@ -529,6 +529,10 @@ void Engine::UpdateSemantics(int64_t view_id,
std::move(actions));
}
void Engine::SetApplicationLocale(std::string locale) {
delegate_.OnEngineSetApplicationLocale(std::move(locale));
}
void Engine::SetSemanticsTreeEnabled(bool enabled) {
delegate_.OnEngineSetSemanticsTreeEnabled(enabled);
}

View File

@ -161,6 +161,13 @@ class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate {
SemanticsNodeUpdates updates,
CustomAccessibilityActionUpdates actions) = 0;
//--------------------------------------------------------------------------
/// @brief Framework sets the application locale.
///
/// @param[in] locale The application locale in BCP 47 format.
///
virtual void OnEngineSetApplicationLocale(std::string locale) = 0;
//--------------------------------------------------------------------------
/// @brief When the Framework starts or stops generating semantics
/// tree,
@ -1029,6 +1036,9 @@ class Engine final : public RuntimeDelegate, PointerDataDispatcher::Delegate {
SemanticsNodeUpdates update,
CustomAccessibilityActionUpdates actions) override;
// |RuntimeDelegate|
void SetApplicationLocale(std::string locale) override;
// |RuntimeDelegate|
void SetSemanticsTreeEnabled(bool enabled) override;

View File

@ -57,6 +57,10 @@ class MockDelegate : public Engine::Delegate {
OnEngineUpdateSemantics,
(int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates),
(override));
MOCK_METHOD(void,
OnEngineSetApplicationLocale,
(const std::string),
(override));
MOCK_METHOD(void, OnEngineSetSemanticsTreeEnabled, (bool), (override));
MOCK_METHOD(void,
OnEngineHandlePlatformMessage,

View File

@ -64,6 +64,10 @@ class MockDelegate : public Engine::Delegate {
OnEngineUpdateSemantics,
(int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates),
(override));
MOCK_METHOD(void,
OnEngineSetApplicationLocale,
(const std::string),
(override));
MOCK_METHOD(void, OnEngineSetSemanticsTreeEnabled, (bool), (override));
MOCK_METHOD(void,
OnEngineHandlePlatformMessage,
@ -116,6 +120,7 @@ class MockRuntimeDelegate : public RuntimeDelegate {
UpdateSemantics,
(int64_t, SemanticsNodeUpdates, CustomAccessibilityActionUpdates),
(override));
MOCK_METHOD(void, SetApplicationLocale, (const std::string), (override));
MOCK_METHOD(void, SetSemanticsTreeEnabled, (bool), (override));
MOCK_METHOD(void,
HandlePlatformMessage,

View File

@ -130,6 +130,10 @@ void PlatformView::UpdateSemantics(
// NOLINTNEXTLINE(performance-unnecessary-value-param)
CustomAccessibilityActionUpdates actions) {}
void PlatformView::SetApplicationLocale(
std::string locale // NOLINT(performance-unnecessary-value-param)
) {}
void PlatformView::SetSemanticsTreeEnabled(
bool enabled // NOLINT(performance-unnecessary-value-param)
) {}

View File

@ -514,6 +514,14 @@ class PlatformView {
SemanticsNodeUpdates updates,
CustomAccessibilityActionUpdates actions);
//----------------------------------------------------------------------------
/// @brief Used by the framework to set application locale in the
/// embedding
///
/// @param[in] locale The application locale in BCP 47 format.
///
virtual void SetApplicationLocale(std::string locale);
//----------------------------------------------------------------------------
/// @brief Used by the framework to tell the embedder to prepare or clear
/// resoruce for accepting semantics tree.

View File

@ -1448,6 +1448,20 @@ void Shell::OnEngineUpdateSemantics(int64_t view_id,
});
}
// |Engine::Delegate|
void Shell::OnEngineSetApplicationLocale(std::string locale) {
FML_DCHECK(is_set_up_);
FML_DCHECK(task_runners_.GetUITaskRunner()->RunsTasksOnCurrentThread());
task_runners_.GetPlatformTaskRunner()->RunNowOrPostTask(
task_runners_.GetPlatformTaskRunner(),
[view = platform_view_->GetWeakPtr(), locale_holder = std::move(locale)] {
if (view) {
view->SetApplicationLocale(locale_holder);
}
});
}
// |Engine::Delegate|
void Shell::OnEngineSetSemanticsTreeEnabled(bool enabled) {
FML_DCHECK(is_set_up_);

View File

@ -675,6 +675,9 @@ class Shell final : public PlatformView::Delegate,
SemanticsNodeUpdates update,
CustomAccessibilityActionUpdates actions) override;
// |Engine::Delegate|
void OnEngineSetApplicationLocale(std::string locale) override;
// |Engine::Delegate|
void OnEngineSetSemanticsTreeEnabled(bool enabled) override;

View File

@ -29,6 +29,10 @@ class MockPlatformViewAndroidJNI : public PlatformViewAndroidJNI {
std::vector<std::string> strings,
std::vector<std::vector<uint8_t>> string_attribute_args),
(override));
MOCK_METHOD(void,
FlutterViewSetApplicationLocale,
(const std::string locale),
(override));
MOCK_METHOD(void,
FlutterViewUpdateCustomAccessibilityActions,
(std::vector<uint8_t> actions_buffer,

View File

@ -803,6 +803,16 @@ public class FlutterJNI {
}
}
/** Invoked by native to set application locale in Android. */
@SuppressWarnings("unused")
@UiThread
private void setApplicationLocale(@NonNull String locale) {
ensureRunningOnMainThread();
if (accessibilityDelegate != null) {
accessibilityDelegate.setLocale(locale);
}
}
/**
* Invoked by native to send new custom accessibility events from Flutter to Android.
*
@ -1631,6 +1641,13 @@ public class FlutterJNI {
@NonNull ByteBuffer buffer,
@NonNull String[] strings,
@NonNull ByteBuffer[] stringAttributeArgs);
/**
* Sets the locale for the assistive technologies.
*
* <p>Must be called on the main thread
*/
void setLocale(@NonNull String locale);
}
public interface AsyncWaitForVsyncDelegate {

View File

@ -227,6 +227,16 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
// a bitmask whose values comes from {@link AccessibilityFeature}.
private int accessibilityFeatureFlags = 0;
// The default locale for assistive technologies in BCP 47 format.
//
// For example "en-US", "de-DE", "fr-FR".
@Nullable private String defaultLocale;
@VisibleForTesting
public void setLocale(@NonNull String locale) {
defaultLocale = locale;
}
// The {@code SemanticsNode} within Flutter that currently has the focus of Android's input
// system.
//
@ -372,6 +382,11 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
}
AccessibilityBridge.this.updateSemantics(buffer, strings, stringAttributeArgs);
}
@Override
public void setLocale(String locale) {
AccessibilityBridge.this.setLocale(locale);
}
};
// Listener that is notified when accessibility is turned on/off.
@ -2795,6 +2810,21 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
return null;
}
/**
* Returns the effective locale for this semantics node after taking app default locale into
* account.
*
* <p>Can be null if there is no preference.
*
* @return the effective locale.
*/
private @Nullable String getEffectiveLocale() {
if (locale != null && !locale.isEmpty()) {
return locale;
}
return accessibilityBridge.defaultLocale;
}
private void updateRecursively(
float[] ancestorTransform, Set<SemanticsNode> visitedObjects, boolean forceUpdate) {
visitedObjects.add(this);
@ -2890,7 +2920,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
return new AccessibilityStringBuilder()
.addString(value)
.addAttributes(valueAttributes)
.addLocale(locale)
.addLocale(getEffectiveLocale())
.build();
}
@ -2899,7 +2929,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
.addString(label)
.addAttributes(labelAttributes)
.addUrl(linkUrl)
.addLocale(locale)
.addLocale(getEffectiveLocale())
.build();
}
@ -2907,7 +2937,7 @@ public class AccessibilityBridge extends AccessibilityNodeProvider {
return new AccessibilityStringBuilder()
.addString(hint)
.addAttributes(hintAttributes)
.addLocale(locale)
.addLocale(getEffectiveLocale())
.build();
}

View File

@ -33,6 +33,10 @@ class JNIMock final : public PlatformViewAndroidJNI {
std::vector<std::string> strings,
std::vector<std::vector<uint8_t>> string_attribute_args),
(override));
MOCK_METHOD(void,
FlutterViewSetApplicationLocale,
(std::string locale),
(override));
MOCK_METHOD(void,
FlutterViewUpdateCustomAccessibilityActions,

View File

@ -63,6 +63,13 @@ class PlatformViewAndroidJNI {
std::vector<std::string> strings,
std::vector<std::vector<uint8_t>> string_attribute_args) = 0;
//----------------------------------------------------------------------------
/// @brief Set application locale to a given language.
///
/// @note Must be called from the platform thread.
///
virtual void FlutterViewSetApplicationLocale(std::string locale) = 0;
//----------------------------------------------------------------------------
/// @brief Sends new custom accessibility events.
///

View File

@ -325,6 +325,11 @@ void PlatformViewAndroid::UpdateSemantics(
platform_view_android_delegate_.UpdateSemantics(update, actions);
}
// |PlatformView|
void PlatformViewAndroid::SetApplicationLocale(std::string locale) {
jni_facade_->FlutterViewSetApplicationLocale(std::move(locale));
}
void PlatformViewAndroid::RegisterExternalTexture(
int64_t texture_id,
const fml::jni::ScopedJavaGlobalRef<jobject>& surface_texture) {

View File

@ -144,6 +144,9 @@ class PlatformViewAndroid final : public PlatformView {
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// |PlatformView|
void SetApplicationLocale(std::string locale) override;
// |PlatformView|
void HandlePlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message) override;

View File

@ -69,6 +69,8 @@ static jfieldID g_jni_shell_holder_field = nullptr;
"(ILjava/nio/ByteBuffer;)V") \
V(g_update_semantics_method, updateSemantics, \
"(Ljava/nio/ByteBuffer;[Ljava/lang/String;[Ljava/nio/ByteBuffer;)V") \
V(g_set_application_locale_method, setApplicationLocale, \
"(Ljava/lang/String;)V") \
V(g_on_display_platform_view_method, onDisplayPlatformView, \
"(IIIIIIILio/flutter/embedding/engine/mutatorsstack/" \
"FlutterMutatorsStack;)V") \
@ -1358,6 +1360,24 @@ void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessage(
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewSetApplicationLocale(
std::string locale) {
JNIEnv* env = fml::jni::AttachCurrentThread();
auto java_object = java_object_.get(env);
if (java_object.is_null()) {
return;
}
fml::jni::ScopedJavaLocalRef<jstring> jlocale =
fml::jni::StringToJavaString(env, locale);
env->CallVoidMethod(java_object.obj(), g_set_application_locale_method,
jlocale.obj());
FML_CHECK(fml::jni::CheckException(env));
}
void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse(
int responseId,
std::unique_ptr<fml::Mapping> data) {

View File

@ -34,6 +34,8 @@ class PlatformViewAndroidJNIImpl final : public PlatformViewAndroidJNI {
std::vector<std::string> strings,
std::vector<std::vector<uint8_t>> string_attribute_args) override;
void FlutterViewSetApplicationLocale(std::string locale) override;
void FlutterViewUpdateCustomAccessibilityActions(
std::vector<uint8_t> actions_buffer,
std::vector<std::string> strings) override;

View File

@ -885,6 +885,91 @@ public class AccessibilityBridgeTest {
assertEquals(actual.getSpanEnd(localeSpan), actual.length());
}
@Test
@Config(minSdk = API_LEVELS.FLUTTER_MIN)
public void itSetsDefaultLocale() {
AccessibilityChannel mockChannel = mock(AccessibilityChannel.class);
AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class);
AccessibilityManager mockManager = mock(AccessibilityManager.class);
View mockRootView = mock(View.class);
Context context = mock(Context.class);
when(mockRootView.getContext()).thenReturn(context);
when(context.getPackageName()).thenReturn("test");
AccessibilityBridge accessibilityBridge =
setUpBridge(
/* rootAccessibilityView= */ mockRootView,
/* accessibilityChannel= */ mockChannel,
/* accessibilityManager= */ mockManager,
/* contentResolver= */ null,
/* accessibilityViewEmbedder= */ mockViewEmbedder,
/* platformViewsAccessibilityDelegate= */ null);
ViewParent mockParent = mock(ViewParent.class);
when(mockRootView.getParent()).thenReturn(mockParent);
when(mockManager.isEnabled()).thenReturn(true);
TestSemanticsNode root = new TestSemanticsNode();
root.id = 0;
root.label = "label";
accessibilityBridge.setLocale("es-MX");
TestSemanticsUpdate testSemanticsUpdate = root.toUpdate();
testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge);
AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0);
SpannableString actual = (SpannableString) nodeInfo.getContentDescription();
assertEquals(actual.toString(), "label");
Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class);
assertEquals(objectSpans.length, 1);
LocaleSpan localeSpan = (LocaleSpan) objectSpans[0];
assertEquals(localeSpan.getLocale().toLanguageTag(), "es-MX");
assertEquals(actual.getSpanStart(localeSpan), 0);
assertEquals(actual.getSpanEnd(localeSpan), actual.length());
}
@Test
@Config(minSdk = API_LEVELS.FLUTTER_MIN)
public void itPrioritizesSectionLocale() {
AccessibilityChannel mockChannel = mock(AccessibilityChannel.class);
AccessibilityViewEmbedder mockViewEmbedder = mock(AccessibilityViewEmbedder.class);
AccessibilityManager mockManager = mock(AccessibilityManager.class);
View mockRootView = mock(View.class);
Context context = mock(Context.class);
when(mockRootView.getContext()).thenReturn(context);
when(context.getPackageName()).thenReturn("test");
AccessibilityBridge accessibilityBridge =
setUpBridge(
/* rootAccessibilityView= */ mockRootView,
/* accessibilityChannel= */ mockChannel,
/* accessibilityManager= */ mockManager,
/* contentResolver= */ null,
/* accessibilityViewEmbedder= */ mockViewEmbedder,
/* platformViewsAccessibilityDelegate= */ null);
ViewParent mockParent = mock(ViewParent.class);
when(mockRootView.getParent()).thenReturn(mockParent);
when(mockManager.isEnabled()).thenReturn(true);
TestSemanticsNode root = new TestSemanticsNode();
root.id = 0;
root.label = "label";
// Sets both section locale and main locale.
root.locale = "fr-FR";
accessibilityBridge.setLocale("es-MX");
TestSemanticsUpdate testSemanticsUpdate = root.toUpdate();
testSemanticsUpdate.sendUpdateToBridge(accessibilityBridge);
AccessibilityNodeInfo nodeInfo = accessibilityBridge.createAccessibilityNodeInfo(0);
SpannableString actual = (SpannableString) nodeInfo.getContentDescription();
assertEquals(actual.toString(), "label");
Object[] objectSpans = actual.getSpans(0, actual.length(), Object.class);
assertEquals(objectSpans.length, 1);
LocaleSpan localeSpan = (LocaleSpan) objectSpans[0];
// Prioritizes section locale over main locale.
assertEquals(localeSpan.getLocale().toLanguageTag(), "fr-FR");
assertEquals(actual.getSpanStart(localeSpan), 0);
assertEquals(actual.getSpanEnd(localeSpan), actual.length());
}
@Test
@Config(minSdk = API_LEVELS.FLUTTER_MIN)
public void itSetsTextCorrectly() {

View File

@ -48,6 +48,7 @@ typedef void (^FlutterKeyboardAnimationCallback)(fml::TimePoint);
@property(nonatomic, readonly) BOOL isPresentingViewController;
@property(nonatomic, readonly) BOOL isVoiceOverRunning;
@property(nonatomic, strong) FlutterKeyboardManager* keyboardManager;
@property(nonatomic, readwrite) NSString* applicationLocale;
/**
* @brief Whether the status bar is preferred hidden.

View File

@ -459,10 +459,10 @@ CGRect ConvertRectToGlobal(SemanticsObject* reference, CGRect local_rect) {
return nil;
}
if (self.node.locale.empty()) {
return nil;
if (!self.node.locale.empty()) {
return @(self.node.locale.data());
}
return @(self.node.locale.data());
return self.bridge->GetDefaultLocale();
}
- (bool)isFocusable {

View File

@ -585,6 +585,37 @@ const float kFloatCompareEpsilon = 0.001;
XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"es-MX"]);
}
- (void)testFlutterSemanticsObjectUseDefaultLocale {
flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge();
mock->isVoiceOverRunningValue = true;
fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock);
fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr();
flutter::SemanticsNode node;
mock->mockedLocale = @"es-MX";
FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0];
[object setSemanticsNode:&node];
XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"es-MX"]);
}
- (void)testFlutterSemanticsObjectPrioritizedSectionLocale {
flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge();
mock->isVoiceOverRunningValue = true;
fml::WeakPtrFactory<flutter::AccessibilityBridgeIos> factory(mock);
fml::WeakPtr<flutter::AccessibilityBridgeIos> bridge = factory.GetWeakPtr();
flutter::SemanticsNode node;
// Set both locales.
mock->mockedLocale = @"es-MX";
node.locale = "zh-TW";
FlutterSemanticsObject* object = [[FlutterSemanticsObject alloc] initWithBridge:bridge uid:0];
[object setSemanticsNode:&node];
// node.locale takes priority.
XCTAssertTrue([object.accessibilityLanguage isEqualToString:@"zh-TW"]);
}
- (void)testFlutterSemanticsObjectLocaleNil {
flutter::testing::MockAccessibilityBridge* mock = new flutter::testing::MockAccessibilityBridge();
mock->isVoiceOverRunningValue = true;

View File

@ -39,6 +39,8 @@ class MockAccessibilityBridge : public AccessibilityBridgeIos {
bool isVoiceOverRunning() const override { return isVoiceOverRunningValue; }
UIView* view() const override { return view_; }
UIView<UITextInput>* textInputView() override { return nil; }
NSString* GetDefaultLocale() override { return mockedLocale; }
void DispatchSemanticsAction(int32_t id, SemanticsAction action) override {
SemanticsActionObservation observation(id, action);
observations.push_back(observation);
@ -54,6 +56,7 @@ class MockAccessibilityBridge : public AccessibilityBridgeIos {
FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; }
std::vector<SemanticsActionObservation> observations;
bool isVoiceOverRunningValue;
NSString* mockedLocale;
private:
UIView* view_;
@ -80,6 +83,7 @@ class MockAccessibilityBridgeNoWindow : public AccessibilityBridgeIos {
}
void AccessibilityObjectDidBecomeFocused(int32_t id) override {}
void AccessibilityObjectDidLoseFocus(int32_t id) override {}
NSString* GetDefaultLocale() override { return nil; }
FlutterPlatformViewsController* GetPlatformViewsController() const override { return nil; }
std::vector<SemanticsActionObservation> observations;
bool isVoiceOverRunningValue;

View File

@ -62,6 +62,7 @@ class AccessibilityBridge final : public AccessibilityBridgeIos {
fml::MallocMapping args) override;
void AccessibilityObjectDidBecomeFocused(int32_t id) override;
void AccessibilityObjectDidLoseFocus(int32_t id) override;
NSString* GetDefaultLocale() override { return view_controller_.applicationLocale; }
UIView<UITextInput>* textInputView() override;

View File

@ -39,6 +39,7 @@ class AccessibilityBridgeIos {
* The input id is the uid of the newly focused SemanticObject.
*/
virtual void AccessibilityObjectDidLoseFocus(int32_t id) = 0;
virtual NSString* GetDefaultLocale() = 0;
virtual FlutterPlatformViewsController* GetPlatformViewsController() const = 0;
};

View File

@ -13,6 +13,7 @@
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h"
#import "flutter/shell/platform/darwin/ios/ios_context.h"
#import "flutter/shell/platform/darwin/ios/ios_external_view_embedder.h"
@ -110,6 +111,9 @@ class PlatformViewIOS final : public PlatformView {
flutter::SemanticsNodeUpdates update,
flutter::CustomAccessibilityActionUpdates actions) override;
// |PlatformView|
void SetApplicationLocale(std::string locale) override;
// |PlatformView|
std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override;

View File

@ -159,6 +159,12 @@ void PlatformViewIOS::UpdateSemantics(int64_t view_id,
}
}
// |PlatformView|
void PlatformViewIOS::SetApplicationLocale(std::string locale) {
FML_DCHECK(owner_controller_);
owner_controller_.applicationLocale = locale.empty() ? nil : @(locale.data());
}
// |PlatformView|
void PlatformViewIOS::SetSemanticsTreeEnabled(bool enabled) {
FML_DCHECK(owner_controller_);

View File

@ -20,6 +20,8 @@
@property(nonatomic, readonly) std::weak_ptr<flutter::AccessibilityBridgeMac> accessibilityBridge;
@property(nonatomic, nullable) NSString* applicationLocale;
/**
* Returns YES if provided event is being currently redispatched by keyboard manager.
*/

View File

@ -5,7 +5,7 @@ contains the build-time dependencies of the Android embedding of the Engine,
and the dependencies of the in-tree testing framework. The Android embedder is
shipped to Flutter end-users, but these build-time dependencies are not.
Therefore, the license script can skip over the destination of the CIPD package
in an Engine checkout at `src/third_party/android_embedding_dependencies`.
in an Engine checkout at `src/flutter/third_party/android_embedding_dependencies`.
Even so, the CIPD package should contain a LICENSE file, and the instructions
below explain how to fetch the license information for the dependencies.
@ -26,7 +26,7 @@ below explain how to fetch the license information for the dependencies.
1. Examine the file `./build/reports/license/license-dependency.xml`. If it
contains licenses other than "The Apache License, Version 2.0" or something
very similar, STOP. Ask Hixie for adivce on how to proceed.
1. Copy or move the `lib/` directory to `src/third_party/android_embedding_dependencies/`,
1. Copy or move the `lib/` directory to `src/flutter/third_party/android_embedding_dependencies/`,
overwriting its contents, and ensure the Android build still works.
1. Run `cipd create --pkg-def cipd.yaml -tag last_updated:"$version_tag"` where
`$version_tag` is the output of `date +%Y-%m-%dT%T%z`.

View File

@ -33,6 +33,7 @@ allprojects {
apply plugin: "com.android.application"
android {
namespace "io.flutter.licensecheck"
compileSdk 36
}

View File

@ -78,7 +78,7 @@ class _HomeState extends State<Home> with TickerProviderStateMixin<Home> {
@override
Widget build(BuildContext context) {
return NavigatorPopHandler(
onPop: () {
onPopWithResult: (void result) {
final NavigatorState navigator = navigatorKeys[selectedIndex].currentState!;
navigator.pop();
},

View File

@ -96,12 +96,14 @@ class _WindowsTable extends StatelessWidget {
context: context,
controller: regular,
),
DialogWindowController() => throw UnimplementedError(),
};
}
static String _getWindowTypeName(BaseWindowController controller) {
return switch (controller) {
RegularWindowController() => 'Regular',
DialogWindowController() => 'Dialog',
};
}

View File

@ -33,6 +33,7 @@ class WindowContent extends StatelessWidget {
controller: regular,
child: MaterialApp(home: RegularWindowContent(window: regular)),
),
DialogWindowController() => throw UnimplementedError(),
};
}
}

View File

@ -66,23 +66,21 @@ const List<double> _kDisabledDarkGradientOpacities = <double>[0.08, 0.14];
/// deselected. The values are of type `T`, the type parameter of the
/// [CupertinoRadio] class. Enums are commonly used for this purpose.
///
/// The radio button itself does not maintain any state. Instead, selecting the
/// radio invokes the [onChanged] callback, passing [value] as a parameter. If
/// [groupValue] and [value] match, this radio will be selected. Most widgets
/// will respond to [onChanged] by calling [State.setState] to update the
/// radio button's [groupValue].
/// This widget typically has a [RadioGroup] ancestor, which takes in a
/// [RadioGroup.groupValue], and the [CupertinoRadio] under it with matching
/// [value] will be selected.
///
/// {@tool dartpad}
/// Here is an example of CupertinoRadio widgets wrapped in CupertinoListTiles.
///
/// The currently selected character is passed into `groupValue`, which is
/// The currently selected character is passed into `RadioGroup.groupValue`, which is
/// maintained by the example's `State`. In this case, the first [CupertinoRadio]
/// will start off selected because `_character` is initialized to
/// `SingingCharacter.lafayette`.
///
/// If the second radio button is pressed, the example's state is updated
/// with `setState`, updating `_character` to `SingingCharacter.jefferson`.
/// This causes the buttons to rebuild with the updated `groupValue`, and
/// This causes the buttons to rebuild with the updated `RadioGroup.groupValue`, and
/// therefore the selection of the second button.
///
/// ** See code in examples/api/lib/cupertino/radio/cupertino_radio.0.dart **

View File

@ -55,7 +55,7 @@ const double _kInnerRadius = 4.5;
///
/// If the second radio button is pressed, the example's state is updated
/// with `setState`, updating `_character` to `SingingCharacter.jefferson`.
/// This causes the buttons to rebuild with the updated `groupValue`, and
/// This causes the buttons to rebuild with the updated `RadioGroup.groupValue`, and
/// therefore the selection of the second button.
///
/// Requires one of its ancestors to be a [Material] widget.

View File

@ -50,7 +50,7 @@ enum _RadioType { material, adaptive }
/// This widget does not coordinate the [selected] state and the
/// [checked] state; to have the list tile appear selected when the
/// radio button is the selected radio button, set [selected] to true
/// when [value] matches [groupValue].
/// when [value] matches [RadioGroup.groupValue].
///
/// The radio button is shown on the left by default in left-to-right languages
/// (i.e. the leading edge). This can be changed using [controlAffinity]. The

View File

@ -159,7 +159,9 @@ mixin class RegularWindowControllerDelegate {
/// {@tool snippet}
/// An example usage might look like:
///
///
/// ```dart
/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable.
/// // ignore_for_file: invalid_use_of_internal_member
/// import 'package:flutter/widgets.dart';
/// import 'package:flutter/material.dart';
@ -181,7 +183,7 @@ mixin class RegularWindowControllerDelegate {
/// {@end-tool}
///
/// Children of a [RegularWindow] widget can access the [RegularWindowController]
/// via the [WindowControllerScope] inherited widget.
/// via the [WindowScope] inherited widget.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
@ -190,6 +192,7 @@ abstract class RegularWindowController extends BaseWindowController {
///
/// Upon construction, the window is created by the platform.
///
/// {@template flutter.widgets.windowing.constraints}
/// The [preferredSize] is the preferred content size of the window.
/// This might not be honored by the platform. This is the size that
/// the platform will try to apply to the window when it is created. In contrast,
@ -209,6 +212,7 @@ abstract class RegularWindowController extends BaseWindowController {
///
/// If both [preferredSize] and [preferredConstraints] are null,
/// then the platform will use its own default size for the window.
/// {@endtemplate}
///
/// The [title] argument configures the window's initial title.
/// If omitted, some platforms might fall back to the app's name.
@ -372,6 +376,250 @@ abstract class RegularWindowController extends BaseWindowController {
void setFullscreen(bool fullscreen, {Display? display});
}
/// Delegate class for dialog window controller.
///
/// {@macro flutter.widgets.windowing.experimental}
///
/// See also:
///
/// * [DialogWindowController], the controller that creates and manages dialog windows.
/// * [DialogWindow], the widget for a dialog window.
/// * [RegularWindowControllerDelegate], the delegate for regular window controllers.
@internal
mixin class DialogWindowControllerDelegate {
/// Invoked when the user attempts to close the window.
///
/// The default implementation destroys the window. Subclasses
/// can override the behavior to delay or prevent the window from closing.
///
/// {@macro flutter.widgets.windowing.experimental}
///
/// See also:
///
/// * [onWindowDestroyed], which is invoked after the window is closed.
@internal
void onWindowCloseRequested(DialogWindowController controller) {
if (!isWindowingEnabled) {
throw UnsupportedError(_kWindowingDisabledErrorMessage);
}
controller.destroy();
}
/// Invoked after the window is closed.
///
/// {@macro flutter.widgets.windowing.experimental}
///
/// See also:
///
/// * [onWindowCloseRequested], which is invoked when the user attempts to close the window.
@internal
void onWindowDestroyed() {
if (!isWindowingEnabled) {
throw UnsupportedError(_kWindowingDisabledErrorMessage);
}
}
}
/// A controller for a dialog window.
///
/// Two types of dialogs are supported:
/// * Modal dialogs: created with a non-null parent. These dialogs are modal
/// to the parent, do not have a system menu, and are not selectable from the
/// window switcher.
/// * Modeless dialogs: created with a null parent. These dialogs can be
/// minimized (but not maximized), and have a disabled close button.
///
/// This class does not interact with the widget tree. Instead, it is typically
/// provided to the [DialogWindow] widget, which renders the content inside the
/// dialog window.
///
/// The user of this class is responsible for managing the lifecycle of the window.
/// When the window is no longer needed, the user should call [destroy] on this
/// controller to release the resources associated with the window.
///
/// {@tool snippet}
/// An example usage might look like:
///
/// ```dart
/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable.
/// // ignore_for_file: invalid_use_of_internal_member
/// import 'package:flutter/widgets.dart';
/// import 'package:flutter/material.dart';
/// import 'package:flutter/src/widgets/_window.dart';
///
/// void main() {
/// runWidget(
/// RegularWindow(
/// controller: RegularWindowController(
/// preferredSize: const Size(800, 600),
/// preferredConstraints: const BoxConstraints(minWidth: 640, minHeight: 480),
/// title: 'Example Window',
/// ),
/// child: const MyApp()
/// )
/// );
/// }
///
/// class MyApp extends StatelessWidget {
/// const MyApp({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// home: DialogWindow(
/// controller: DialogWindowController(
/// preferredSize: const Size(400, 300),
/// parent: WindowScope.of(context),
/// title: 'Example Dialog'
/// ),
/// child: const Text('Hello, World!')
/// )
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// Children of a [DialogWindow] widget can access the [DialogWindowController]
/// via the [WindowScope] inherited widget.
///
/// {@macro flutter.widgets.windowing.experimental}
abstract class DialogWindowController extends BaseWindowController {
/// Creates a [DialogWindowController] with the provided properties.
///
/// Upon construction, the window is created by the platform.
///
/// {@macro flutter.widgets.windowing.constraints}
///
/// The [parent] argument specifies the parent window of this dialog.
///
/// If the [parent] is null, then the dialog is modeless. Such dialogs can
/// be minimized but not maximized. They also have a disabled close button.
///
/// If the [parent] is non-null, then the dialog is modal to the parent.
/// Such dialogs do not have a system menu. They are also not selectable
/// from the window switcher and they are closed when the parent is closed.
///
/// The [title] argument configures the window's initial title.
/// If omitted, some platforms might fall back to the app's name.
///
/// The [delegate] argument can be used to listen to the window's
/// lifecycle. For example, it can be used to save state before
/// a window is closed.
///
/// {@macro flutter.widgets.windowing.experimental}
factory DialogWindowController({
Size? preferredSize,
BoxConstraints? preferredConstraints,
BaseWindowController? parent,
String? title,
DialogWindowControllerDelegate? delegate,
}) {
WidgetsFlutterBinding.ensureInitialized();
final WindowingOwner owner = WidgetsBinding.instance.windowingOwner;
return owner.createDialogWindowController(
delegate: delegate ?? DialogWindowControllerDelegate(),
preferredSize: preferredSize,
preferredConstraints: preferredConstraints,
title: title,
parent: parent,
);
}
/// Creates an empty [DialogWindowController].
///
/// This method is only intended to be used by subclasses of the
/// [DialogWindowController].
///
/// Users who want to instantiate a new [DialogWindowController] should
/// always use the factory method to create a controller that is valid
/// for their particular platform.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
@protected
DialogWindowController.empty();
/// The parent controller of this dialog, if any.
///
/// If null, this dialog is modeless.
/// If non-null, this dialog is modal to the parent.
BaseWindowController? get parent;
/// The current title of the window.
///
/// This might differ from the requested title.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
String get title;
/// Whether the window is currently activated.
///
/// If `true` this means that the window is currently focused and
/// can receive user input.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
bool get isActivated;
/// Whether or not window is currently minimized.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
bool get isMinimized;
/// Request change to the content size of the window.
///
/// The [size] describes the new requested window size. If the size disagrees
/// with the current constraints placed upon the window, the platform might
/// clamp the size within the constraints.
///
/// The platform is free to ignore this request.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
void setSize(Size size);
/// Request change to the constraints of the window.
///
/// The [constraints] describes the new constraints that the window should
/// satisfy. If the constraints disagree with the current size of the window,
/// the platform might resize the window to satisfy the new constraints.
///
/// The platform is free to ignore this request.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
void setConstraints(BoxConstraints constraints);
/// Request change for the window title.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
void setTitle(String title);
/// Requests that the window be displayed in its current size and position.
///
/// The platform may also give the window input focus and bring it to the
/// top of the window stack. However, this behavior is platform-dependent.
///
/// If the window is minimized, the window returns to the size and position
/// that it had before that state was applied. The window will also be
/// brought to the top of the window stack.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
void activate();
/// Requests window to be minimized.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
void setMinimized(bool minimized);
}
/// [WindowingOwner] is responsible for creating and managing window controllers.
///
/// A custom implementation can be provided by setting [WidgetsBinding.windowingOwner].
@ -394,6 +642,22 @@ abstract class WindowingOwner {
String? title,
});
/// Creates a [DialogWindowController] with the provided properties.
///
/// Most app developers should use [DialogWindowController]'s constructor
/// instead of calling this method directly. This method allows platforms
/// to inject platform-specific logic.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
DialogWindowController createDialogWindowController({
required DialogWindowControllerDelegate delegate,
Size? preferredSize,
BoxConstraints? preferredConstraints,
BaseWindowController? parent,
String? title,
});
/// Returns whether the application has any top level windows created by this
/// windowing owner.
///
@ -435,6 +699,17 @@ class _WindowingOwnerUnsupported extends WindowingOwner {
throw UnsupportedError(errorMessage);
}
@override
DialogWindowController createDialogWindowController({
required DialogWindowControllerDelegate delegate,
Size? preferredSize,
BoxConstraints? preferredConstraints,
BaseWindowController? parent,
String? title,
}) {
throw UnsupportedError(errorMessage);
}
@override
bool hasTopLevelWindows() {
throw UnsupportedError(errorMessage);
@ -458,6 +733,7 @@ class _WindowingOwnerUnsupported extends WindowingOwner {
/// An example usage might look like:
///
/// ```dart
/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable.
/// // ignore_for_file: invalid_use_of_internal_member
/// import 'package:flutter/widgets.dart';
/// import 'package:flutter/material.dart';
@ -523,6 +799,107 @@ class RegularWindow extends StatelessWidget {
}
}
/// The [DialogWindow] widget provides a way to render a dialog window in the
/// widget tree.
///
/// The provided [controller] creates the native window that backs
/// the widget. The [child] widget is rendered into this newly created window.
///
/// When a [DialogWindow] widget is removed from the tree, the window that was created
/// by the [controller] remains valid until the caller destroys it by calling
/// [DialogWindowController.destroy].
///
/// Widgets in the same tree as the [child] widget will have access to the
/// [DialogWindowController] via the [WindowScope] widget.
///
/// {@tool snippet}
/// An example usage might look like:
///
/// ```dart
/// // TODO(mattkae): remove invalid_use_of_internal_member ignore comment when this API is stable.
/// // ignore_for_file: invalid_use_of_internal_member
/// import 'package:flutter/widgets.dart';
/// import 'package:flutter/material.dart';
/// import 'package:flutter/src/widgets/_window.dart';
///
/// void main() {
/// runWidget(
/// RegularWindow(
/// controller: RegularWindowController(
/// preferredSize: const Size(800, 600),
/// preferredConstraints: const BoxConstraints(minWidth: 640, minHeight: 480),
/// title: 'Example Window',
/// ),
/// child: const MyApp()
/// )
/// );
/// }
///
/// class MyApp extends StatelessWidget {
/// const MyApp({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return MaterialApp(
/// home: DialogWindow(
/// controller: DialogWindowController(
/// preferredSize: const Size(400, 300),
/// parent: WindowScope.of(context),
/// title: 'Example Dialog'
/// ),
/// child: const Text('Hello, World!')
/// )
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
class DialogWindow extends StatelessWidget {
/// Creates a dialog window widget.
///
/// The [controller] creates the native backing window into which the
/// [child] widget is rendered.
///
/// It is up to the caller to destroy the window by calling
/// [DialogWindowController.destroy] when the window is no longer needed.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
DialogWindow({super.key, required this.controller, required this.child}) {
if (!isWindowingEnabled) {
throw UnsupportedError(_kWindowingDisabledErrorMessage);
}
}
/// Controller for this widget.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
final DialogWindowController controller;
/// The content rendered into this window.
///
/// {@macro flutter.widgets.windowing.experimental}
@internal
final Widget child;
/// {@macro flutter.widgets.windowing.experimental}
@internal
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: controller,
builder: (BuildContext context, Widget? widget) => WindowScope(
controller: controller,
child: View(view: controller.rootView, child: child),
),
);
}
}
enum _WindowControllerAspect { contentSize, title, activated, maximized, minimized, fullscreen }
/// Provides descendants with access to the [BaseWindowController] associated with
@ -537,6 +914,7 @@ enum _WindowControllerAspect { contentSize, title, activated, maximized, minimiz
/// See also:
///
/// * [RegularWindow], the widget to create a regular window.
/// * [DialogWindow], the widget to create a dialog window.
@internal
class WindowScope extends InheritedModel<_WindowControllerAspect> {
/// Creates a new [WindowScope].
@ -565,8 +943,8 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
/// Returns the [BaseWindowController] for the window that hosts the given context.
///
/// {@template flutter.widgets.windowing.windowControllerScope.of}
/// If there is no [WindowControllerScope] in scope, this method
/// {@template flutter.widgets.windowing.WindowScope.of}
/// If there is no [WindowScope] in scope, this method
/// will throw a [TypeError] exception in release builds, and throws
/// a descriptive [FlutterError] in debug builds.
///
@ -580,7 +958,9 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
/// See also:
///
/// * [RegularWindowController], the controller for regular top-level windows.
/// * [DialogWindowController], the controller for dialog windows.
/// * [RegularWindow], the widget for a regular window.
/// * [DialogWindow], the widget for a dialog window.
/// * [maybeOf], which doesn't throw or assert if it doesn't find a
/// [WindowScope] ancestor. It returns null instead.
@internal
@ -595,7 +975,9 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
/// See also:
///
/// * [RegularWindowController], the controller for regular top-level windows.
/// * [DialogWindowController], the controller for dialog windows.
/// * [RegularWindow], the widget for a regular window.
/// * [DialogWindow], the widget for a dialog window.
/// * [of], which will throw if it doesn't find a [WindowScope] ancestor,
/// instead of returning null.
@internal
@ -648,6 +1030,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
final BaseWindowController controller = _of(context, _WindowControllerAspect.title);
return switch (controller) {
RegularWindowController() => controller.title,
DialogWindowController() => controller.title,
};
}
@ -668,6 +1051,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.title,
DialogWindowController() => controller.title,
};
}
@ -689,6 +1073,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
final BaseWindowController controller = _of(context, _WindowControllerAspect.activated);
return switch (controller) {
RegularWindowController() => controller.isActivated,
DialogWindowController() => controller.isActivated,
};
}
@ -710,6 +1095,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.isActivated,
DialogWindowController() => controller.isActivated,
};
}
@ -731,6 +1117,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
final BaseWindowController controller = _of(context, _WindowControllerAspect.minimized);
return switch (controller) {
RegularWindowController() => controller.isMinimized,
DialogWindowController() => controller.isMinimized,
};
}
@ -752,6 +1139,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.isMinimized,
DialogWindowController() => controller.isMinimized,
};
}
@ -773,6 +1161,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
final BaseWindowController controller = _of(context, _WindowControllerAspect.maximized);
return switch (controller) {
RegularWindowController() => controller.isMaximized,
DialogWindowController() => false,
};
}
@ -794,6 +1183,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.isMaximized,
DialogWindowController() => false,
};
}
@ -816,6 +1206,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.isFullscreen,
DialogWindowController() => false,
};
}
@ -837,6 +1228,7 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
return switch (controller) {
RegularWindowController() => controller.isFullscreen,
DialogWindowController() => false,
};
}
@ -898,26 +1290,34 @@ class WindowScope extends InheritedModel<_WindowControllerAspect> {
_WindowControllerAspect.title => switch (controller) {
final RegularWindowController regular =>
regular.title != (oldWidget.controller as RegularWindowController).title,
final DialogWindowController dialog =>
dialog.title != (oldWidget.controller as DialogWindowController).title,
},
_WindowControllerAspect.activated => switch (controller) {
final RegularWindowController regular =>
regular.isActivated !=
(oldWidget.controller as RegularWindowController).isActivated,
final DialogWindowController dialog =>
dialog.isActivated != (oldWidget.controller as DialogWindowController).isActivated,
},
_WindowControllerAspect.maximized => switch (controller) {
final RegularWindowController regular =>
regular.isMaximized !=
(oldWidget.controller as RegularWindowController).isMaximized,
DialogWindowController() => false,
},
_WindowControllerAspect.minimized => switch (controller) {
final RegularWindowController regular =>
regular.isMinimized !=
(oldWidget.controller as RegularWindowController).isMinimized,
final DialogWindowController dialog =>
dialog.isMinimized != (oldWidget.controller as DialogWindowController).isMinimized,
},
_WindowControllerAspect.fullscreen => switch (controller) {
final RegularWindowController regular =>
regular.isFullscreen !=
(oldWidget.controller as RegularWindowController).isFullscreen,
DialogWindowController() => false,
},
},
);

View File

@ -148,6 +148,18 @@ class WindowingOwnerWin32 extends WindowingOwner {
);
}
@internal
@override
DialogWindowController createDialogWindowController({
required DialogWindowControllerDelegate delegate,
Size? preferredSize,
BoxConstraints? preferredConstraints,
BaseWindowController? parent,
String? title,
}) {
throw UnimplementedError('Dialog windows are not yet implemented on Windows.');
}
/// Register a new [WindowsMessageHandler].
///
/// The handler will be triggered for unhandled messages for all top level

View File

@ -634,6 +634,14 @@ class _LocalizationsState extends State<Localizations> {
Locale? get locale => _locale;
Locale? _locale;
set locale(Locale? locale) {
assert(locale != null);
if (_locale == locale) {
return;
}
WidgetsBinding.instance.platformDispatcher.setApplicationLocale(locale!);
_locale = locale;
}
@override
void initState() {
@ -668,7 +676,7 @@ class _LocalizationsState extends State<Localizations> {
void load(Locale locale) {
final Iterable<LocalizationsDelegate<dynamic>> delegates = widget.delegates;
if (delegates.isEmpty) {
_locale = locale;
this.locale = locale;
return;
}
@ -681,7 +689,7 @@ class _LocalizationsState extends State<Localizations> {
if (typeToResources != null) {
// All of the delegates' resources loaded synchronously.
_typeToResources = typeToResources!;
_locale = locale;
this.locale = locale;
} else {
// - Don't rebuild the dependent widgets until the resources for the new locale
// have finished loading. Until then the old locale will continue to be used.
@ -692,7 +700,7 @@ class _LocalizationsState extends State<Localizations> {
if (mounted) {
setState(() {
_typeToResources = value;
_locale = locale;
this.locale = locale;
});
}
RendererBinding.instance.allowFirstFrame();

View File

@ -61,6 +61,24 @@ void main() {
expect(find.text('loaded'), findsOneWidget);
});
testWidgets('Locale is sent to engine if this is a top level Localizations', (
WidgetTester tester,
) async {
final FakeLocalizationsDelegate delegate = FakeLocalizationsDelegate();
await tester.pumpWidget(
Localizations(
locale: const Locale('fo'),
isApplicationLevel: true,
delegates: <LocalizationsDelegate<dynamic>>[WidgetsLocalizationsDelegate(), delegate],
child: const Text('loaded'),
),
);
delegate.completer.complete('foo');
await tester.idle();
await tester.pump();
expect(tester.binding.platformDispatcher.applicationLocale, const Locale('fo'));
});
testWidgets('Localizations.localeOf throws when no localizations exist', (
WidgetTester tester,
) async {

View File

@ -9,7 +9,7 @@ import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
export 'dart:ui' show SemanticsAction, SemanticsFlag;
export 'dart:ui' show SemanticsAction, SemanticsFlag, SemanticsFlags;
export 'package:flutter/rendering.dart' show SemanticsData;
const String _matcherHelp =
@ -62,7 +62,7 @@ class TestSemantics {
this.currentValueLength,
this.identifier = '',
this.hintOverrides,
}) : assert(flags is int || flags is List<SemanticsFlag>),
}) : assert(flags is int || flags is List<SemanticsFlag> || flags is SemanticsFlags),
assert(actions is int || actions is List<SemanticsAction>),
tags = tags?.toSet() ?? <SemanticsTag>{};
@ -95,7 +95,7 @@ class TestSemantics {
this.identifier = '',
this.hintOverrides,
}) : id = 0,
assert(flags is int || flags is List<SemanticsFlag>),
assert(flags is int || flags is List<SemanticsFlag> || flags is SemanticsFlags),
assert(actions is int || actions is List<SemanticsAction>),
rect = TestSemantics.rootRect,
tags = tags?.toSet() ?? <SemanticsTag>{};
@ -138,7 +138,7 @@ class TestSemantics {
this.currentValueLength,
this.identifier = '',
this.hintOverrides,
}) : assert(flags is int || flags is List<SemanticsFlag>),
}) : assert(flags is int || flags is List<SemanticsFlag> || flags is SemanticsFlags),
assert(actions is int || actions is List<SemanticsAction>),
transform = _applyRootChildScale(transform),
tags = tags?.toSet() ?? <SemanticsTag>{};
@ -149,12 +149,15 @@ class TestSemantics {
/// they are created.
final int? id;
/// The [SemanticsFlag]s set on this node.
/// The SemanticsFlags on this node.
///
/// There are two ways to specify this property: as an `int` that encodes the
/// flags as a bit field, or as a `List<SemanticsFlag>` that are _on_.
/// There are three ways to specify this property: as an `int` that encodes the
/// flags as a bit field, or as a `List<SemanticsFlag>` that are _on_, or as a `SemanticsFlags`.
///
/// Using `List<SemanticsFlag>` is recommended due to better readability.
/// Using `SemanticsFlags` is recommended.
///
/// The `int` and `List<SemanticsFlag>` types are considered deprecated as they
/// have limited bits and only support the first 31 flags.
final dynamic flags;
/// The [SemanticsAction]s set on this node.
@ -323,14 +326,25 @@ class TestSemantics {
final SemanticsData nodeData = node.getSemanticsData();
final int flagsBitmask = flags is int
? flags as int
: (flags as List<SemanticsFlag>).fold<int>(
0,
(int bitmask, SemanticsFlag flag) => bitmask | flag.index,
);
if (flagsBitmask != nodeData.flags) {
return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.');
if (flags is SemanticsFlags) {
if (flags != nodeData.flagsCollection) {
return fail(
'expected node id $id to have flags $flags but found flags ${nodeData.flagsCollection}.',
);
}
}
// the bitmask flags only support first 31 flags.
else {
final int flagsBitmask = flags is int
? flags as int
: (flags as List<SemanticsFlag>).fold<int>(
0,
(int bitmask, SemanticsFlag flag) => bitmask | flag.index,
);
if (flagsBitmask != nodeData.flags) {
return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.');
}
}
final int actionsBitmask = actions is int
@ -505,8 +519,9 @@ class TestSemantics {
if (id != null) {
buf.writeln('$indent id: $id,');
}
if (flags is int && flags != 0 ||
flags is List<SemanticsFlag> && (flags as List<SemanticsFlag>).isNotEmpty) {
if ((flags is int && flags != 0) ||
(flags is List<SemanticsFlag> && (flags as List<SemanticsFlag>).isNotEmpty) ||
(flags is SemanticsFlags && (flags as SemanticsFlags) != SemanticsFlags.none)) {
buf.writeln('$indent flags: ${SemanticsTester._flagsToSemanticsFlagExpression(flags)},');
}
if (actions is int && actions != 0 ||
@ -659,6 +674,7 @@ class SemanticsTester {
TextDirection? textDirection,
List<SemanticsAction>? actions,
List<SemanticsFlag>? flags,
SemanticsFlags? flagsCollection,
Set<SemanticsTag>? tags,
double? scrollPosition,
double? scrollExtentMax,
@ -719,7 +735,16 @@ class SemanticsTester {
return false;
}
}
if (flags != null) {
if (flagsCollection != null) {
final SemanticsFlags expectedFlags = flagsCollection;
final SemanticsFlags actualFlags = node.getSemanticsData().flagsCollection;
if (expectedFlags != actualFlags) {
return false;
}
}
// `flags` are deprecated and only support the first 31 flags.
else if (flags != null) {
final int expectedFlags = flags.fold<int>(
0,
(int value, SemanticsFlag flag) => value | flag.index,
@ -827,7 +852,9 @@ class SemanticsTester {
static String _flagsToSemanticsFlagExpression(dynamic flags) {
Iterable<SemanticsFlag> list;
if (flags is int) {
if (flags is SemanticsFlags) {
return '<SemanticsFlag>[${flags.toStrings().join(', ')}]';
} else if (flags is int) {
list = SemanticsFlag.values.where((SemanticsFlag flag) => (flag.index & flags) != 0);
} else {
list = flags as List<SemanticsFlag>;
@ -1048,6 +1075,7 @@ class _IncludesNodeWith extends Matcher {
this.textDirection,
this.actions,
this.flags,
this.flagsCollection,
this.tags,
this.scrollPosition,
this.scrollExtentMax,
@ -1060,6 +1088,7 @@ class _IncludesNodeWith extends Matcher {
value != null ||
actions != null ||
flags != null ||
flagsCollection != null ||
tags != null ||
increasedValue != null ||
decreasedValue != null ||
@ -1081,6 +1110,7 @@ class _IncludesNodeWith extends Matcher {
final TextDirection? textDirection;
final List<SemanticsAction>? actions;
final List<SemanticsFlag>? flags;
final SemanticsFlags? flagsCollection;
final Set<SemanticsTag>? tags;
final double? scrollPosition;
final double? scrollExtentMax;
@ -1104,6 +1134,7 @@ class _IncludesNodeWith extends Matcher {
textDirection: textDirection,
actions: actions,
flags: flags,
flagsCollection: flagsCollection,
tags: tags,
scrollPosition: scrollPosition,
scrollExtentMax: scrollExtentMax,
@ -1168,6 +1199,7 @@ Matcher includesNodeWith({
TextDirection? textDirection,
List<SemanticsAction>? actions,
List<SemanticsFlag>? flags,
SemanticsFlags? flagsCollection,
Set<SemanticsTag>? tags,
double? scrollPosition,
double? scrollExtentMax,
@ -1188,6 +1220,7 @@ Matcher includesNodeWith({
decreasedValue: decreasedValue,
actions: actions,
flags: flags,
flagsCollection: flagsCollection,
tags: tags,
scrollPosition: scrollPosition,
scrollExtentMax: scrollExtentMax,

View File

@ -2,6 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
@ -46,4 +48,105 @@ void main() {
);
semantics.dispose();
});
testWidgets('Semantics tester support flags as an int', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
selected: true,
child: Container(),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'test1',
rect: TestSemantics.fullScreen,
flags: SemanticsFlag.hasSelectedState.index | SemanticsFlag.isSelected.index,
),
],
),
),
);
semantics.dispose();
});
testWidgets('Semantics tester support flags as a list of SemanticsFlag', (
WidgetTester tester,
) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
selected: true,
child: Container(),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'test1',
rect: TestSemantics.fullScreen,
flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected],
),
],
),
),
);
semantics.dispose();
});
testWidgets('Semantics tester support flags as a SemanticsFlags', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test1',
textDirection: TextDirection.ltr,
selected: true,
child: Container(),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'test1',
rect: TestSemantics.fullScreen,
flags: SemanticsFlags(isSelected: Tristate.isTrue),
),
],
),
),
);
semantics.dispose();
});
}

View File

@ -7,6 +7,9 @@ import 'package:flutter/src/foundation/_features.dart' show isWindowingEnabled;
import 'package:flutter/src/widgets/_window.dart'
show
BaseWindowController,
DialogWindow,
DialogWindowController,
DialogWindowControllerDelegate,
RegularWindow,
RegularWindowController,
RegularWindowControllerDelegate,
@ -18,8 +21,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'multi_view_testing.dart';
class _StubWindowController extends RegularWindowController {
_StubWindowController(WidgetTester tester) : super.empty() {
class _StubRegularWindowController extends RegularWindowController {
_StubRegularWindowController(WidgetTester tester) : super.empty() {
rootView = FakeView(tester.view);
}
@ -66,6 +69,45 @@ class _StubWindowController extends RegularWindowController {
void destroy() {}
}
class _StubDialogWindowController extends DialogWindowController {
_StubDialogWindowController(WidgetTester tester) : super.empty() {
rootView = FakeView(tester.view);
}
@override
BaseWindowController? get parent => null;
@override
Size get contentSize => Size.zero;
@override
String get title => 'Stub Window';
@override
bool get isActivated => true;
@override
bool get isMinimized => false;
@override
void setSize(Size size) {}
@override
void setConstraints(BoxConstraints constraints) {}
@override
void setTitle(String title) {}
@override
void activate() {}
@override
void setMinimized(bool minimized) {}
@override
void destroy() {}
}
void main() {
group('Windowing', () {
group('isWindowingEnabled is false', () {
@ -86,6 +128,14 @@ void main() {
);
});
test('default WindowingOwner throws when accessing createDialogWindowController', () {
final WindowingOwner owner = createDefaultWindowingOwner();
expect(
() => owner.createDialogWindowController(delegate: DialogWindowControllerDelegate()),
throwsUnsupportedError,
);
});
test('default WindowingOwner throws when accessing hasTopLevelWindows', () {
final WindowingOwner owner = createDefaultWindowingOwner();
expect(() => owner.hasTopLevelWindows(), throwsUnsupportedError);
@ -93,7 +143,20 @@ void main() {
testWidgets('RegularWindow throws UnsupportedError', (WidgetTester tester) async {
expect(
() => RegularWindow(controller: _StubWindowController(tester), child: const Text('Test')),
() => RegularWindow(
controller: _StubRegularWindowController(tester),
child: const Text('Test'),
),
throwsUnsupportedError,
);
});
testWidgets('DialogWindow throws UnsupportedError', (WidgetTester tester) async {
expect(
() => DialogWindow(
controller: _StubDialogWindowController(tester),
child: const Text('Test'),
),
throwsUnsupportedError,
);
});
@ -112,7 +175,7 @@ void main() {
});
testWidgets('RegularWindow does not throw', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -120,8 +183,17 @@ void main() {
);
});
testWidgets('Can access WindowScope.of', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Dialog does not throw', (WidgetTester tester) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(controller: controller, child: Container()),
);
});
testWidgets('Can access WindowScope.of for regular windows', (WidgetTester tester) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -138,8 +210,28 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.of for dialog windows', (WidgetTester tester) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final BaseWindowController scope = WindowScope.of(context);
expect(scope, isA<DialogWindowController>());
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -156,8 +248,28 @@ void main() {
);
});
testWidgets('Can access WindowScope.contentSizeOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeOf for dialog windows', (WidgetTester tester) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final BaseWindowController? scope = WindowScope.maybeOf(context);
expect(scope, isA<DialogWindowController>());
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.contentSizeOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -174,8 +286,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeContentSizeOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.contentSizeOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final Size size = WindowScope.contentSizeOf(context);
expect(size, equals(Size.zero));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeContentSizeOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -192,8 +326,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.titleOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeContentSizeOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final Size? size = WindowScope.maybeContentSizeOf(context);
expect(size, equals(Size.zero));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.titleOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -210,8 +366,28 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeTitleOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.titleOf for dialog windows', (WidgetTester tester) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final String title = WindowScope.titleOf(context);
expect(title, equals('Stub Window'));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeTitleOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -228,8 +404,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.isActivatedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeTitleOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final String? title = WindowScope.maybeTitleOf(context);
expect(title, equals('Stub Window'));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.isActivatedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -246,8 +444,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeIsActivatedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.isActivatedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool isActivated = WindowScope.isActivatedOf(context);
expect(isActivated, equals(true));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeIsActivatedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -264,8 +484,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.isMinimizedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeIsActivatedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool? isActivated = WindowScope.maybeIsActivatedOf(context);
expect(isActivated, equals(true));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.isMinimizedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -282,8 +524,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeIsMinimizedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.isMinimizedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool isMinimized = WindowScope.isMinimizedOf(context);
expect(isMinimized, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeIsMinimizedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -300,8 +564,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.isMaximizedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeIsMinimizedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool? isMinimized = WindowScope.maybeIsMinimizedOf(context);
expect(isMinimized, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.isMaximizedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -318,8 +604,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeIsMaximizedOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.isMaximizedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool isMaximized = WindowScope.isMaximizedOf(context);
expect(isMaximized, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeIsMaximizedOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -336,8 +644,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.isFullscreenOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.maybeIsMaximizedOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool? isMaximized = WindowScope.maybeIsMaximizedOf(context);
expect(isMaximized, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.isFullscreenOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -354,8 +684,30 @@ void main() {
);
});
testWidgets('Can access WindowScope.maybeIsFullscreenOf', (WidgetTester tester) async {
final _StubWindowController controller = _StubWindowController(tester);
testWidgets('Can access WindowScope.isFullscreenOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool isFullscreen = WindowScope.isFullscreenOf(context);
expect(isFullscreen, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
testWidgets('Can access WindowScope.maybeIsFullscreenOf for regular windows', (
WidgetTester tester,
) async {
final _StubRegularWindowController controller = _StubRegularWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
@ -371,6 +723,26 @@ void main() {
),
);
});
testWidgets('Can access WindowScope.maybeIsFullscreenOf for dialog windows', (
WidgetTester tester,
) async {
final _StubDialogWindowController controller = _StubDialogWindowController(tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
wrapWithView: false,
DialogWindow(
controller: controller,
child: Builder(
builder: (BuildContext context) {
final bool? isFullscreen = WindowScope.maybeIsFullscreenOf(context);
expect(isFullscreen, equals(false));
return const SizedBox.shrink();
},
),
),
);
});
});
});
}

View File

@ -163,7 +163,7 @@ class MinimumTapTargetGuideline extends AccessibilityGuideline {
}
// skip node if it is touching the edge scrollable, since it might
// be partially scrolled offscreen.
if (current.hasFlag(SemanticsFlag.hasImplicitScrolling) &&
if (current.flagsCollection.hasImplicitScrolling &&
_isAtBoundary(paintBounds, current.rect)) {
return result;
}
@ -207,11 +207,11 @@ class MinimumTapTargetGuideline extends AccessibilityGuideline {
// Skip node if it has no actions, or is marked as hidden.
if ((!data.hasAction(ui.SemanticsAction.longPress) &&
!data.hasAction(ui.SemanticsAction.tap)) ||
data.hasFlag(ui.SemanticsFlag.isHidden)) {
data.flagsCollection.isHidden) {
return true;
}
// Skip links https://www.w3.org/WAI/WCAG21/Understanding/target-size.html
if (data.hasFlag(ui.SemanticsFlag.isLink)) {
if (data.flagsCollection.isLink) {
return true;
}
return false;
@ -253,8 +253,8 @@ class LabeledTapTargetGuideline extends AccessibilityGuideline {
});
if (node.isMergedIntoParent ||
node.isInvisible ||
node.hasFlag(ui.SemanticsFlag.isHidden) ||
node.hasFlag(ui.SemanticsFlag.isTextField)) {
node.flagsCollection.isHidden ||
node.flagsCollection.isTextField) {
return result;
}
final SemanticsData data = node.getSemanticsData();
@ -346,12 +346,11 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline {
Evaluation result = const Evaluation.pass();
// Skip disabled nodes, as they not required to pass contrast check.
final bool isDisabled =
node.hasFlag(ui.SemanticsFlag.hasEnabledState) && !node.hasFlag(ui.SemanticsFlag.isEnabled);
final bool isDisabled = node.flagsCollection.isEnabled == ui.Tristate.isFalse;
if (node.isInvisible ||
node.isMergedIntoParent ||
node.hasFlag(ui.SemanticsFlag.isHidden) ||
node.flagsCollection.isHidden ||
isDisabled) {
return result;
}
@ -481,8 +480,7 @@ class MinimumTextContrastGuideline extends AccessibilityGuideline {
///
/// Skip routes which might have labels, and nodes without any text.
bool shouldSkipNode(SemanticsData data) =>
data.hasFlag(ui.SemanticsFlag.scopesRoute) ||
(data.label.trim().isEmpty && data.value.trim().isEmpty);
data.flagsCollection.scopesRoute || (data.label.trim().isEmpty && data.value.trim().isEmpty);
/// Returns if a rectangle of node is off the screen.
///

View File

@ -13,6 +13,7 @@
/// @docImport 'widget_tester.dart';
library;
import 'dart:ui' as ui;
import 'package:clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
@ -74,17 +75,6 @@ class SemanticsController {
SemanticsAction.scrollRight.index |
SemanticsAction.scrollToOffset.index;
/// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java).
static final int _importantFlagsForAccessibility =
SemanticsFlag.hasCheckedState.index |
SemanticsFlag.hasToggledState.index |
SemanticsFlag.hasEnabledState.index |
SemanticsFlag.isButton.index |
SemanticsFlag.isTextField.index |
SemanticsFlag.isFocusable.index |
SemanticsFlag.isSlider.index |
SemanticsFlag.isInMutuallyExclusiveGroup.index;
final WidgetController _controller;
/// Attempts to find the [SemanticsNode] of first result from `finder`.
@ -353,7 +343,7 @@ class SemanticsController {
final SemanticsData data = node.getSemanticsData();
// If the node scopes a route, it doesn't matter what other flags/actions it
// has, it is _not_ important for accessibility, so we short circuit.
if (data.hasFlag(SemanticsFlag.scopesRoute)) {
if (data.flagsCollection.scopesRoute) {
return false;
}
@ -362,7 +352,17 @@ class SemanticsController {
return true;
}
final bool hasImportantFlag = data.flags & _importantFlagsForAccessibility != 0;
/// Based on Android's FOCUSABLE_FLAGS. See [flutter/engine/AccessibilityBridge.java](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/android/io/flutter/view/AccessibilityBridge.java).
final bool hasImportantFlag =
data.flagsCollection.isChecked != ui.CheckedState.none ||
data.flagsCollection.isToggled != ui.Tristate.none ||
data.flagsCollection.isEnabled != ui.Tristate.none ||
data.flagsCollection.isButton ||
data.flagsCollection.isTextField ||
data.flagsCollection.isFocused != ui.Tristate.none ||
data.flagsCollection.isSlider ||
data.flagsCollection.isInMutuallyExclusiveGroup;
if (hasImportantFlag) {
return true;
}

View File

@ -1351,7 +1351,7 @@ class _FirstWidgetFinder extends ChainedFinder with _FirstFinderMixin<Element> {
mixin _LastFinderMixin<CandidateType> on ChainedFinderMixin<CandidateType> {
@override
String describeMatch(Plurality plurality) {
return '${parent.describeMatch(plurality)} (ignoring all but first)';
return '${parent.describeMatch(plurality)} (ignoring all but last)';
}
@override

View File

@ -2454,38 +2454,38 @@ class _MatchesSemanticsData extends Matcher {
required String? onLongPressHint,
required this.customActions,
required this.children,
}) : flags = <SemanticsFlag, bool>{
SemanticsFlag.hasCheckedState: ?hasCheckedState,
SemanticsFlag.isChecked: ?isChecked,
SemanticsFlag.isCheckStateMixed: ?isCheckStateMixed,
SemanticsFlag.isSelected: ?isSelected,
SemanticsFlag.hasSelectedState: ?hasSelectedState,
SemanticsFlag.isButton: ?isButton,
SemanticsFlag.isSlider: ?isSlider,
SemanticsFlag.isKeyboardKey: ?isKeyboardKey,
SemanticsFlag.isLink: ?isLink,
SemanticsFlag.isTextField: ?isTextField,
SemanticsFlag.isReadOnly: ?isReadOnly,
SemanticsFlag.isFocused: ?isFocused,
SemanticsFlag.isFocusable: ?isFocusable,
SemanticsFlag.hasEnabledState: ?hasEnabledState,
SemanticsFlag.isEnabled: ?isEnabled,
SemanticsFlag.isInMutuallyExclusiveGroup: ?isInMutuallyExclusiveGroup,
SemanticsFlag.isHeader: ?isHeader,
SemanticsFlag.isObscured: ?isObscured,
SemanticsFlag.isMultiline: ?isMultiline,
SemanticsFlag.namesRoute: ?namesRoute,
SemanticsFlag.scopesRoute: ?scopesRoute,
SemanticsFlag.isHidden: ?isHidden,
SemanticsFlag.isImage: ?isImage,
SemanticsFlag.isLiveRegion: ?isLiveRegion,
SemanticsFlag.hasToggledState: ?hasToggledState,
SemanticsFlag.isToggled: ?isToggled,
SemanticsFlag.hasImplicitScrolling: ?hasImplicitScrolling,
SemanticsFlag.hasExpandedState: ?hasExpandedState,
SemanticsFlag.isExpanded: ?isExpanded,
SemanticsFlag.hasRequiredState: ?hasRequiredState,
SemanticsFlag.isRequired: ?isRequired,
}) : flags = <String, bool>{
'hasCheckedState': ?hasCheckedState,
'isChecked': ?isChecked,
'isCheckStateMixed': ?isCheckStateMixed,
'isSelected': ?isSelected,
'hasSelectedState': ?hasSelectedState,
'isButton': ?isButton,
'isSlider': ?isSlider,
'isKeyboardKey': ?isKeyboardKey,
'isLink': ?isLink,
'isTextField': ?isTextField,
'isReadOnly': ?isReadOnly,
'isFocused': ?isFocused,
'isFocusable': ?isFocusable,
'hasEnabledState': ?hasEnabledState,
'isEnabled': ?isEnabled,
'isInMutuallyExclusiveGroup': ?isInMutuallyExclusiveGroup,
'isHeader': ?isHeader,
'isObscured': ?isObscured,
'isMultiline': ?isMultiline,
'namesRoute': ?namesRoute,
'scopesRoute': ?scopesRoute,
'isHidden': ?isHidden,
'isImage': ?isImage,
'isLiveRegion': ?isLiveRegion,
'hasToggledState': ?hasToggledState,
'isToggled': ?isToggled,
'hasImplicitScrolling': ?hasImplicitScrolling,
'hasExpandedState': ?hasExpandedState,
'isExpanded': ?isExpanded,
'hasRequiredState': ?hasRequiredState,
'isRequired': ?isRequired,
},
actions = <SemanticsAction, bool>{
SemanticsAction.tap: ?hasTapAction,
@ -2546,7 +2546,7 @@ class _MatchesSemanticsData extends Matcher {
/// 2. If the flag/action maps to `false`, then it must not be present in the SemanticData
/// 3. If the flag/action is not in the map, then it will not be validated against
final Map<SemanticsAction, bool> actions;
final Map<SemanticsFlag, bool> flags;
final Map<String, bool> flags;
@override
Description describe(Description description, [String? index]) {
@ -2598,27 +2598,27 @@ class _MatchesSemanticsData extends Matcher {
.toList();
if (expectedActions.isNotEmpty) {
description.add(' with actions: ${_createEnumsSummary(expectedActions)} ');
description.add(' with actions: ${_createSemanticsActionSummary(expectedActions)} ');
}
if (notExpectedActions.isNotEmpty) {
description.add(' without actions: ${_createEnumsSummary(notExpectedActions)} ');
description.add(' without actions: ${_createSemanticsActionSummary(notExpectedActions)} ');
}
}
if (flags.isNotEmpty) {
final List<SemanticsFlag> expectedFlags = flags.entries
.where((MapEntry<ui.SemanticsFlag, bool> e) => e.value)
.map((MapEntry<ui.SemanticsFlag, bool> e) => e.key)
final List<String> expectedFlags = flags.entries
.where((MapEntry<String, bool> e) => e.value)
.map((MapEntry<String, bool> e) => e.key)
.toList();
final List<SemanticsFlag> notExpectedFlags = flags.entries
.where((MapEntry<ui.SemanticsFlag, bool> e) => !e.value)
.map((MapEntry<ui.SemanticsFlag, bool> e) => e.key)
final List<String> notExpectedFlags = flags.entries
.where((MapEntry<String, bool> e) => !e.value)
.map((MapEntry<String, bool> e) => e.key)
.toList();
if (expectedFlags.isNotEmpty) {
description.add(' with flags: ${_createEnumsSummary(expectedFlags)} ');
description.add(' with flags: ${expectedFlags.join(',')} ');
}
if (notExpectedFlags.isNotEmpty) {
description.add(' without flags: ${_createEnumsSummary(notExpectedFlags)} ');
description.add(' without flags: ${notExpectedFlags.join(', ')} ');
}
}
if (textDirection != null) {
@ -2803,7 +2803,7 @@ class _MatchesSemanticsData extends Matcher {
if (unexpectedActions.isNotEmpty || missingActions.isNotEmpty) {
return failWithDescription(
matchState,
'missing actions: ${_createEnumsSummary(missingActions)} unexpected actions: ${_createEnumsSummary(unexpectedActions)}',
'missing actions: ${_createSemanticsActionSummary(missingActions)} unexpected actions: ${_createSemanticsActionSummary(unexpectedActions)}',
);
}
}
@ -2848,17 +2848,18 @@ class _MatchesSemanticsData extends Matcher {
}
}
if (flags.isNotEmpty) {
final List<SemanticsFlag> unexpectedFlags = <SemanticsFlag>[];
final List<SemanticsFlag> missingFlags = <SemanticsFlag>[];
for (final MapEntry<ui.SemanticsFlag, bool> flagEntry in flags.entries) {
final ui.SemanticsFlag flag = flagEntry.key;
final Map<String, bool> foundFlags = _stringsMapFromSemanticsFlags(data.flagsCollection);
final List<String> unexpectedFlags = <String>[];
final List<String> missingFlags = <String>[];
for (final MapEntry<String, bool> flagEntry in flags.entries) {
final String flagName = flagEntry.key;
final bool flagExpected = flagEntry.value;
final bool flagPresent = flag.index & data.flags == flag.index;
final bool flagPresent = foundFlags[flagName]!;
if (flagPresent != flagExpected) {
if (flagExpected) {
missingFlags.add(flag);
missingFlags.add(flagName);
} else {
unexpectedFlags.add(flag);
unexpectedFlags.add(flagName);
}
}
}
@ -2866,7 +2867,7 @@ class _MatchesSemanticsData extends Matcher {
if (unexpectedFlags.isNotEmpty || missingFlags.isNotEmpty) {
return failWithDescription(
matchState,
'missing flags: ${_createEnumsSummary(missingFlags)} unexpected flags: ${_createEnumsSummary(unexpectedFlags)}',
'missing flags: ${missingFlags.join(',')} unexpected flags: ${unexpectedFlags.join(',')}',
);
}
}
@ -2897,16 +2898,8 @@ class _MatchesSemanticsData extends Matcher {
return mismatchDescription.add(matchState['failure'] as String);
}
static String _createEnumsSummary<T extends Object>(List<T> enums) {
assert(
T == SemanticsAction || T == SemanticsFlag,
'This method is only intended for lists of SemanticsActions or SemanticsFlags.',
);
if (T == SemanticsAction) {
return '[${(enums as List<SemanticsAction>).map((SemanticsAction d) => d.name).join(', ')}]';
} else {
return '[${(enums as List<SemanticsFlag>).map((SemanticsFlag d) => d.name).join(', ')}]';
}
static String _createSemanticsActionSummary(List<SemanticsAction> enums) {
return '[${enums.map((ui.SemanticsAction d) => d.name).join(', ')}]';
}
}
@ -2949,3 +2942,39 @@ class _DoesNotMatchAccessibilityGuideline extends AsyncMatcher {
return null;
}
}
Map<String, bool> _stringsMapFromSemanticsFlags(SemanticsFlags flagsCollection) {
return <String, bool>{
'hasCheckedState': flagsCollection.isChecked != ui.CheckedState.none,
'isChecked': flagsCollection.isChecked == ui.CheckedState.isTrue,
'isCheckStateMixed': flagsCollection.isChecked == ui.CheckedState.mixed,
'isSelected': flagsCollection.isSelected == ui.Tristate.isTrue,
'hasSelectedState': flagsCollection.isSelected != ui.Tristate.none,
'isButton': flagsCollection.isButton,
'isSlider': flagsCollection.isSlider,
'isKeyboardKey': flagsCollection.isKeyboardKey,
'isLink': flagsCollection.isLink,
'isFocused': flagsCollection.isFocused == ui.Tristate.isTrue,
'isFocusable': flagsCollection.isFocused != ui.Tristate.none,
'isTextField': flagsCollection.isTextField,
'isReadOnly': flagsCollection.isReadOnly,
'hasEnabledState': flagsCollection.isEnabled != ui.Tristate.none,
'isEnabled': flagsCollection.isEnabled == ui.Tristate.isTrue,
'isInMutuallyExclusiveGroup': flagsCollection.isInMutuallyExclusiveGroup,
'isHeader': flagsCollection.isHeader,
'isObscured': flagsCollection.isObscured,
'isMultiline': flagsCollection.isMultiline,
'namesRoute': flagsCollection.namesRoute,
'scopesRoute': flagsCollection.scopesRoute,
'isHidden': flagsCollection.isHidden,
'isImage': flagsCollection.isImage,
'isLiveRegion': flagsCollection.isLiveRegion,
'hasToggledState': flagsCollection.isToggled != ui.Tristate.none,
'isToggled': flagsCollection.isToggled == ui.Tristate.isTrue,
'hasImplicitScrolling': flagsCollection.hasImplicitScrolling,
'hasExpandedState': flagsCollection.isExpanded != ui.Tristate.none,
'isExpanded': flagsCollection.isExpanded == ui.Tristate.isTrue,
'hasRequiredState': flagsCollection.isRequired != ui.Tristate.none,
'isRequired': flagsCollection.isRequired == ui.Tristate.isTrue,
};
}

View File

@ -484,6 +484,14 @@ class TestPlatformDispatcher implements PlatformDispatcher {
bool get semanticsEnabled => _semanticsEnabledTestValue ?? _platformDispatcher.semanticsEnabled;
bool? _semanticsEnabledTestValue;
/// The application locale set during the test.
Locale? applicationLocale;
@override
void setApplicationLocale(Locale locale) {
applicationLocale = locale;
}
/// Hides the real semantics enabled and reports the given
/// [semanticsEnabledTestValue] instead.
// ignore: avoid_setters_without_getters

View File

@ -1655,6 +1655,18 @@ void main() {
expect(finder.found, orderedEquals(expected));
});
});
group('first and last', () {
test('describes first correctly', () {
final _FakeFinder finder = _FakeFinder();
expect(finder.first.toString(describeSelf: true), contains('(ignoring all but first)'));
});
test('describes last correctly', () {
final _FakeFinder finder = _FakeFinder();
expect(finder.last.toString(describeSelf: true), contains('(ignoring all but last)'));
});
});
});
}

View File

@ -97,7 +97,7 @@ object DependencyVersionChecker {
// Java error and warn should align with packages/flutter_tools/lib/src/android/gradle_utils.dart.
@VisibleForTesting internal val warnJavaVersion: JavaVersion = JavaVersion.VERSION_17
@VisibleForTesting internal val errorJavaVersion: JavaVersion = JavaVersion.VERSION_11
@VisibleForTesting internal val errorJavaVersion: JavaVersion = JavaVersion.VERSION_17
@VisibleForTesting internal val warnAGPVersion: AndroidPluginVersion = AndroidPluginVersion(8, 6, 0)

View File

@ -16,6 +16,7 @@ import com.flutter.gradle.DependencyVersionChecker.OUT_OF_SUPPORT_RANGE_PROPERTY
import com.flutter.gradle.DependencyVersionChecker.POTENTIAL_JAVA_FIX
import com.flutter.gradle.DependencyVersionChecker.errorAGPVersion
import com.flutter.gradle.DependencyVersionChecker.errorGradleVersion
import com.flutter.gradle.DependencyVersionChecker.errorJavaVersion
import com.flutter.gradle.DependencyVersionChecker.errorKGPVersion
import com.flutter.gradle.DependencyVersionChecker.errorMinSdkVersion
import com.flutter.gradle.DependencyVersionChecker.getErrorMessage
@ -27,7 +28,6 @@ import com.flutter.gradle.DependencyVersionChecker.getPotentialSDKFix
import com.flutter.gradle.DependencyVersionChecker.getWarnMessage
import com.flutter.gradle.DependencyVersionChecker.warnAGPVersion
import com.flutter.gradle.DependencyVersionChecker.warnGradleVersion
import com.flutter.gradle.DependencyVersionChecker.warnJavaVersion
import com.flutter.gradle.DependencyVersionChecker.warnKGPVersion
import com.flutter.gradle.DependencyVersionChecker.warnMinSdkVersion
import io.mockk.every
@ -154,31 +154,31 @@ class DependencyVersionCheckerTest {
verify(exactly = 0) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) }
}
// No test for Java version in error range, as the lowest supported Java version is also the
// No test for Java version in warn range, as the lowest supported Java version is also the
// lowest possible.
@Test
fun `Java version in warn range results in warning logs`() {
val exampleWarnJavaVersion = JavaVersion.VERSION_16
val mockProject = MockProjectFactory.createMockProjectWithSpecifiedDependencyVersions(javaVersion = exampleWarnJavaVersion)
fun `Java version in error range results in error logs`() {
val exampleErrorJavaVersion = JavaVersion.VERSION_16
val mockProject = MockProjectFactory.createMockProjectWithSpecifiedDependencyVersions(javaVersion = exampleErrorJavaVersion)
val mockExtraPropertiesExtension = mockProject.extra
every { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, false) } returns Unit
every { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) } returns Unit
val mockLogger = mockProject.logger
every { mockLogger.error(any()) } returns Unit
DependencyVersionChecker.checkDependencyVersions(mockProject)
verify {
mockLogger.error(
getWarnMessage(
val dependencyValidationException =
assertFailsWith<DependencyValidationException> { DependencyVersionChecker.checkDependencyVersions(mockProject) }
assert(
dependencyValidationException.message ==
getErrorMessage(
JAVA_NAME,
exampleWarnJavaVersion.toString(),
warnJavaVersion.toString(),
exampleErrorJavaVersion.toString(),
errorJavaVersion.toString(),
POTENTIAL_JAVA_FIX
)
)
}
verify(exactly = 0) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) }
)
verify(exactly = 1) { mockExtraPropertiesExtension.set(OUT_OF_SUPPORT_RANGE_PROPERTY, true) }
}
@Test

View File

@ -59,7 +59,7 @@ const targetSdkVersion = '36';
const ndkVersion = '27.0.12077973';
final minBuildToolsVersion = Version(28, 0, 3);
// Align with packages/flutter_tools/gradle/src/main/kotlin/DependencyVersionChecker.kt.
final errorJavaMinVersionAndroid = Version(11, 0, 0);
final errorJavaMinVersionAndroid = Version(17, 0, 0);
final warnJavaMinVersionAndroid = Version(17, 0, 0);
// Update these when new major versions of Java are supported by new Gradle

View File

@ -448,6 +448,7 @@ final class WidgetPreviewStartCommand extends WidgetPreviewSubCommandBase with C
widgetPreviewScaffoldProject.packageConfig.readAsBytesSync(),
widgetPreviewScaffoldProject.packageConfig.uri,
),
trackWidgetCreation: true,
// Don't try and download canvaskit from the CDN.
useLocalCanvasKit: true,
webEnableHotReload: true,

View File

@ -188,6 +188,7 @@ const nativeAssets = Feature(
environmentOverride: 'FLUTTER_NATIVE_ASSETS',
master: FeatureChannelSetting(available: true, enabledByDefault: true),
beta: FeatureChannelSetting(available: true, enabledByDefault: true),
stable: FeatureChannelSetting(available: true, enabledByDefault: true),
);
/// Enable Dart data assets building and bundling.

View File

@ -1468,11 +1468,11 @@ abstract class ResidentRunner extends ResidentHandlers {
/// of the default URI encoding.
String urlToDisplayString(Uri uri) {
final base = StringBuffer(uri.withoutQueryParameters().toString());
base.write(
uri.queryParameters.keys
.map((String key) => '$key=${uri.queryParameters[key]}')
.join('&'),
);
if (uri.hasQuery) {
base.write(
'?${uri.queryParameters.keys.map((String key) => '$key=${uri.queryParameters[key]}').join('&')}',
);
}
return base.toString();
}

View File

@ -22,7 +22,7 @@ const kManuallyPinnedDependencies = <String, String>{
// Add pinned packages here. Please leave a comment explaining why.
'archive': '3.6.1', // https://github.com/flutter/flutter/issues/115660
'code_assets':
'0.19.6', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes.
'0.19.7', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes.
'dds':
'5.0.3', // 5.0.4 contains bugs described in https://github.com/Dart-Code/Dart-Code/issues/4678.
'flutter_gallery_assets': '1.0.2', // Tests depend on the exact version.
@ -31,7 +31,7 @@ const kManuallyPinnedDependencies = <String, String>{
'hooks':
'0.20.1', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes.
'hooks_runner':
'0.22.1', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes.
'0.23.0', // Under active development with breaking changes until 1.0.0. Manually rolled by @dcharkes.
'material_color_utilities': '0.11.1', // Keep pinned to latest until 1.0.0.
};

View File

@ -11,9 +11,9 @@ import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/diagnostic/diagnostic.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/source/line_info.dart';
import '../base/logger.dart';
import 'preview_details.dart';
@ -33,7 +33,7 @@ typedef PreviewDependencyGraph = Map<PreviewPath, LibraryPreviewNode>;
/// Visitor which detects previews and extracts [PreviewDetails] for later code
/// generation.
class _PreviewVisitor extends RecursiveAstVisitor<void> {
_PreviewVisitor({required LibraryElement2 lib})
_PreviewVisitor({required LibraryElement lib})
: packageName = lib.uri.scheme == 'package' ? lib.uri.pathSegments.first : null;
late final String? packageName;
@ -45,9 +45,12 @@ class _PreviewVisitor extends RecursiveAstVisitor<void> {
MethodDeclaration? _currentMethod;
late Uri _currentScriptUri;
late CompilationUnit _currentUnit;
void findPreviewsInResolvedUnitResult(ResolvedUnitResult unit) {
_scopedVisitChildren(unit.unit, (_) => _currentScriptUri = unit.file.toUri());
_currentScriptUri = unit.file.toUri();
_currentUnit = unit.unit;
_currentUnit.visitChildren(this);
}
/// Handles previews defined on top-level functions.
@ -96,6 +99,10 @@ class _PreviewVisitor extends RecursiveAstVisitor<void> {
if (preview == null) {
return;
}
final LineInfo lineInfo = _currentUnit.lineInfo;
final CharacterLocation location = lineInfo.getLocation(node.offset);
final int line = location.lineNumber;
final int column = location.columnNumber;
if (_currentFunction != null &&
!hasRequiredParams(_currentFunction!.functionExpression.parameters)) {
final TypeAnnotation? returnTypeAnnotation = _currentFunction!.returnType;
@ -105,6 +112,8 @@ class _PreviewVisitor extends RecursiveAstVisitor<void> {
previewEntries.add(
PreviewDetails(
scriptUri: _currentScriptUri,
line: line,
column: column,
packageName: packageName,
functionName: _currentFunction!.name.toString(),
isBuilder: returnType.isWidgetBuilder,
@ -120,6 +129,8 @@ class _PreviewVisitor extends RecursiveAstVisitor<void> {
previewEntries.add(
PreviewDetails(
scriptUri: _currentScriptUri,
line: line,
column: column,
packageName: packageName,
functionName: '$returnType${name == null ? '' : '.$name'}',
isBuilder: false,
@ -136,6 +147,8 @@ class _PreviewVisitor extends RecursiveAstVisitor<void> {
previewEntries.add(
PreviewDetails(
scriptUri: _currentScriptUri,
line: line,
column: column,
packageName: packageName,
functionName: '${parentClass.name}.${_currentMethod!.name}',
isBuilder: returnType.isWidgetBuilder,
@ -194,7 +207,7 @@ final class LibraryPreviewNode {
bool get hasErrors => errors.isNotEmpty;
/// The set of errors found in this library.
final errors = <AnalysisError>[];
final errors = <Diagnostic>[];
/// Determines the set of errors found in this library.
///
@ -203,8 +216,8 @@ final class LibraryPreviewNode {
errors.clear();
for (final String file in files) {
errors.addAll(
((await context.currentSession.getErrors(file)) as ErrorsResult).errors
.where((AnalysisError error) => error.severity == Severity.error)
((await context.currentSession.getErrors(file)) as ErrorsResult).diagnostics
.where((error) => error.severity == Severity.error)
.toList(),
);
}

View File

@ -3,8 +3,8 @@
// found in the LICENSE file.
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element2.dart' as analyzer;
import 'package:analyzer/dart/element/element2.dart';
import 'package:analyzer/dart/element/element.dart' as analyzer;
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:built_collection/built_collection.dart';
import 'package:code_builder/code_builder.dart' as cb;
@ -32,7 +32,9 @@ class PreviewCodeGenerator {
static const _kBuildMultiWidgetPreview = 'buildMultiWidgetPreview';
static const _kBuildWidgetPreview = 'buildWidgetPreview';
static const _kBuildWidgetPreviewError = 'buildWidgetPreviewError';
static const _kColumn = 'column';
static const _kDependencyHasErrors = 'dependencyHasErrors';
static const _kLine = 'line';
static const _kListType = 'List';
static const _kPackageName = 'packageName';
static const _kPackageUri = 'packageUri';
@ -164,6 +166,8 @@ class PreviewCodeGenerator {
final args = <String, cb.Expression>{
_kPackageName: cb.literalString(preview.packageName!),
_kScriptUri: cb.literalString(preview.scriptUri.toString()),
_kLine: cb.literalNum(preview.line),
_kColumn: cb.literalNum(preview.column),
};
// TODO(bkonyi): improve the error related code.
if (libraryDetails.hasErrors || libraryDetails.dependencyHasErrors) {
@ -206,7 +210,7 @@ extension on DartObject {
DartType(isDartCoreInt: true) => cb.literalNum(toIntValue()!),
DartType(isDartCoreString: true) => cb.literalString(toStringValue()!),
DartType(isDartCoreNull: true) => cb.literalNull,
InterfaceType(element3: EnumElement()) => _createEnumInstance(this),
InterfaceType(element: EnumElement()) => _createEnumInstance(this),
InterfaceType() => _createInstance(type, this),
FunctionType() => _createTearoff(toFunctionValue()!),
_ => throw UnsupportedError('Unexpected DartObject type: $runtimeType'),
@ -238,10 +242,10 @@ extension on DartObject {
final ConstructorInvocation constructorInvocation = object.constructorInvocation!;
final ConstructorElement constructor = constructorInvocation.constructor;
final cb.Expression type = cb.refer(
dartType.element3.name3!,
_elementToLibraryIdentifier(dartType.element3),
dartType.element.name!,
_elementToLibraryIdentifier(dartType.element),
);
final String? name = constructor.name3 == 'new' ? null : constructor.name3;
final String? name = constructor.name == 'new' ? null : constructor.name;
final List<cb.Expression> positionalArguments = constructorInvocation.positionalArguments
.map((e) => e.toExpression())

View File

@ -10,6 +10,8 @@ typedef PreviewProperty = ({String key, DartObject object, bool isCallback});
final class PreviewDetails {
PreviewDetails({
required this.scriptUri,
required this.line,
required this.column,
required this.packageName,
required this.functionName,
required this.isBuilder,
@ -20,6 +22,12 @@ final class PreviewDetails {
/// The file:// URI pointing to the script in which the preview is defined.
final Uri scriptUri;
/// The 1-based line at which the Preview annotation was applied.
final int line;
/// The 1-based column at which the Preview annotation was applied.
final int column;
/// The name of the package in which the preview was defined.
///
/// For example, if this preview is defined in 'package:foo/src/bar.dart', this

View File

@ -8,7 +8,7 @@ import 'dart:collection';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/source/source.dart';
import 'package:collection/collection.dart';

View File

@ -58,9 +58,9 @@ dependencies:
pubspec_parse: 1.5.0
graphs: 2.3.2
hooks_runner: 0.22.1
hooks_runner: 0.23.0
hooks: 0.20.1
code_assets: 0.19.6
code_assets: 0.19.7
data_assets: 0.19.3
# We depend on very specific internal implementation details of the
@ -127,4 +127,4 @@ dev_dependencies:
dartdoc:
# Exclude this package from the hosted API docs.
nodoc: true
# PUBSPEC CHECKSUM: sro36f
# PUBSPEC CHECKSUM: 37t3vr

View File

@ -6,7 +6,7 @@ environment:
sdk: {{dartSdkVersionBounds}}
dependencies:
code_assets: ^0.19.6
code_assets: ^0.19.7
hooks: ^0.20.1
logging: ^1.3.0
native_toolchain_c: ^0.17.1

View File

@ -9,6 +9,8 @@ import 'package:widget_preview_scaffold/src/widget_preview.dart';
Iterable<WidgetPreview> buildMultiWidgetPreview({
required String packageName,
required String scriptUri,
required int line,
required int column,
required MultiPreview preview,
required Object? Function() previewFunction,
}) {
@ -16,6 +18,8 @@ Iterable<WidgetPreview> buildMultiWidgetPreview({
(p) => buildWidgetPreview(
packageName: packageName,
scriptUri: scriptUri,
line: line,
column: column,
transformedPreview: p,
previewFunction: previewFunction,
),
@ -25,6 +29,8 @@ Iterable<WidgetPreview> buildMultiWidgetPreview({
WidgetPreview buildWidgetPreview({
required String packageName,
required String scriptUri,
required int line,
required int column,
required Preview transformedPreview,
required Object? Function() previewFunction,
}) {
@ -39,6 +45,8 @@ WidgetPreview buildWidgetPreview({
return WidgetPreview(
builder: previewBuilder,
scriptUri: scriptUri,
line: line,
column: column,
previewData: transformedPreview,
packageName: packageName,
);
@ -47,6 +55,8 @@ WidgetPreview buildWidgetPreview({
WidgetPreview buildWidgetPreviewError({
required String packageName,
required String scriptUri,
required int line,
required int column,
required String packageUri,
required String functionName,
required bool dependencyHasErrors,
@ -58,6 +68,8 @@ WidgetPreview buildWidgetPreviewError({
return WidgetPreview(
builder: () => Text('$functionName: $errorMessage'),
scriptUri: scriptUri,
line: line,
column: column,
previewData: const Preview(group: 'Invalid Previews'),
packageName: packageName,
);

View File

@ -31,15 +31,33 @@ class WidgetPreview {
const WidgetPreview({
required this.builder,
required this.scriptUri,
required this.line,
required this.column,
required this.previewData,
required this.packageName,
});
@visibleForTesting
const WidgetPreview.test({
required this.builder,
required this.previewData,
this.scriptUri = '',
this.line = -1,
this.column = -1,
this.packageName = '',
});
/// The absolute file:// URI pointing to the script containing this preview.
///
/// This matches the URI format sent by IDEs for active location change events.
final String scriptUri;
/// The line at which the Preview annotation was applied.
final int line;
/// The column at which the Preview annotation was applied.
final int column;
/// The name of the package in which a preview was defined.
///
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
@ -104,6 +122,7 @@ class WidgetPreview {
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty<String>('name', name, ifNull: 'not set'))
..add(DiagnosticsProperty<String>('group', previewData.group))
..add(DiagnosticsProperty<Size>('size', size))
..add(DiagnosticsProperty<double>('textScaleFactor', textScaleFactor))
..add(DiagnosticsProperty<PreviewThemeData>('theme', theme))

View File

@ -178,12 +178,16 @@ class NoPreviewsDetectedWidget extends StatelessWidget {
}
}
/// A wrapper that serves as the root entry for a single preview in the widget inspector.
class PreviewWidget extends StatelessWidget {
const PreviewWidget({super.key, required this.preview, required this.child});
final WidgetPreview preview;
final Widget child;
@override
StatelessElement createElement() => PreviewWidgetElement(this);
@override
Widget build(BuildContext context) {
return child;
@ -191,7 +195,9 @@ class PreviewWidget extends StatelessWidget {
@override
String toStringShort() {
final StringBuffer buffer = StringBuffer('@Preview');
final StringBuffer buffer = StringBuffer(
'@${preview.previewData.runtimeType}',
);
if (preview.name != null) {
buffer.write('(name: "${preview.name}")');
}
@ -205,6 +211,12 @@ class PreviewWidget extends StatelessWidget {
}
}
/// A custom [StatelessElement] with the sole purpose of simplifying identifying
/// selections of @Preview annotations in the widget inspector.
class PreviewWidgetElement extends StatelessElement {
PreviewWidgetElement(super.widget);
}
class WidgetPreviewGroupWidget extends StatelessWidget {
const WidgetPreviewGroupWidget({
super.key,

View File

@ -3,7 +3,10 @@
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import 'package:widget_preview_scaffold/src/dtd/editor_service.dart';
import 'package:widget_preview_scaffold/src/widget_preview_rendering.dart';
import 'dtd/dtd_services.dart';
import 'widget_preview.dart';
@ -21,7 +24,11 @@ class WidgetPreviewScaffoldController {
required PreviewsCallback previews,
@visibleForTesting WidgetPreviewScaffoldDtdServices? dtdServicesOverride,
}) : _previews = previews,
dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices();
dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices() {
// Overrides the default WidgetInspectorService instance to handle selection
// events.
_WidgetPreviewScaffoldInspectorService(dtdServices: dtdServices);
}
/// Initializes the controller by establishing a connection to DTD and
/// listening for events.
@ -154,3 +161,77 @@ class WidgetPreviewScaffoldController {
}
}
}
/// A custom [WidgetInspectorService] responsible for routing navigation events
/// to the IDE.
class _WidgetPreviewScaffoldInspectorService with WidgetInspectorService {
_WidgetPreviewScaffoldInspectorService({required this.dtdServices}) {
WidgetInspectorService.instance = this;
}
final WidgetPreviewScaffoldDtdServices dtdServices;
// Keys used to specify the creation location of a widget when serializing a
// DiagnosticsNode to JSON. This location is used by the widget inspector
// to jump to the creation location of a selected widget.
static const kFile = 'fileUri';
static const kLine = 'line';
static const kColumn = 'column';
CodeLocation? _nextNavigationLocation;
@protected
@override
bool setSelection(Object? object, [String? groupName]) {
// The next navigation event sent to `postEvent` will be for this selection.
// Save the location of preview annotation applications so we can override
// the navigation target in `postEvent`.
if (object is PreviewWidgetElement) {
final previewData = (object.widget as PreviewWidget).preview;
_nextNavigationLocation = CodeLocation(
uri: previewData.scriptUri,
line: previewData.line,
column: previewData.column,
);
}
final result = super.setSelection(object, groupName);
_nextNavigationLocation = null;
return result;
}
@override
void postEvent(
String eventKind,
Map<Object, Object?> eventData, {
String stream = 'Extension',
}) {
// It's unlikely that the widget previewer will be connected to directly by
// an IDE via the VM service, so we forward navigation events via the
// Editor DTD service.
if (eventKind == 'navigate') {
CodeLocation? location = _nextNavigationLocation;
if (eventData case {
kFile: final String file,
kLine: final int line,
kColumn: final int column,
} when location == null) {
location = CodeLocation(uri: file, line: line, column: column);
} else if (location != null) {
// If a [PreviewWidgetElement] was selected, we're not navigating to the
// creation location of the widget. Override the location details in the
// event data, just in case an IDE is attached and listening for
// navigation events through the VM service.
// TODO(bkonyi): determine if this is necessary
eventData.addAll(<String, Object>{
kFile: location.uri,
kLine: location.line!,
kColumn: location.column!,
});
}
if (location != null) {
dtdServices.navigateToCode(location);
}
}
super.postEvent(eventKind, eventData, stream: stream);
}
}

View File

@ -297,18 +297,24 @@ List<_i1.WidgetPreview> previews() => [
_i2.buildWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 4,
column: 1,
previewFunction: () => _i3.preview(),
transformedPreview: const _i4.Preview().transform(),
),
_i2.buildWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 10,
column: 1,
previewFunction: () => _i5.barPreview1(),
transformedPreview: const _i4.Preview(group: 'group').transform(),
),
_i2.buildWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 13,
column: 1,
previewFunction: () => _i5.barPreview2(),
transformedPreview:
const _i4.Preview(brightness: _i6.brightnessConstant).transform(),
@ -316,6 +322,8 @@ List<_i1.WidgetPreview> previews() => [
_i2.buildWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 16,
column: 1,
previewFunction: () => _i5.barPreview3(),
transformedPreview: const _i4.Preview(
group: 'group',
@ -334,12 +342,16 @@ List<_i1.WidgetPreview> previews() => [
..._i2.buildMultiWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 51,
column: 1,
previewFunction: () => _i11.preview(),
preview: const _i11.BrightnessPreview(name: 'Foo'),
),
_i2.buildWidgetPreview(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 52,
column: 1,
previewFunction: () => _i11.preview(),
transformedPreview:
const _i11.FixedSizePreview(name: 'Bar').transform(),
@ -347,6 +359,8 @@ List<_i1.WidgetPreview> previews() => [
_i2.buildWidgetPreviewError(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 6,
column: 1,
packageUri: 'package:foo_project/src/error.dart',
functionName: 'preview',
dependencyHasErrors: false,
@ -354,6 +368,8 @@ List<_i1.WidgetPreview> previews() => [
_i2.buildWidgetPreviewError(
packageName: 'foo_project',
scriptUri: 'STRIPPED',
line: 6,
column: 1,
packageUri: 'package:foo_project/src/transitive_error.dart',
functionName: 'preview',
dependencyHasErrors: true,

View File

@ -104,24 +104,24 @@ class PreviewMatcher extends Matcher {
);
checkPropertyMatch(
name: kWrapper,
actual: item.getFirstField(kWrapper)?.toFunctionValue2()?.displayName,
actual: item.getFirstField(kWrapper)?.toFunctionValue()?.displayName,
expected: wrapper,
);
checkPropertyMatch(
name: kTheme,
actual: item.getFirstField(kTheme)?.toFunctionValue2()?.displayName,
actual: item.getFirstField(kTheme)?.toFunctionValue()?.displayName,
expected: theme,
);
final DartObject? actualBrightness = item.getFirstField(kBrightness);
checkPropertyMatch(
name: kBrightness,
actual: (actualBrightness?.isNull ?? true) ? null : actualBrightness!.variable2!.toString(),
actual: (actualBrightness?.isNull ?? true) ? null : actualBrightness!.variable!.toString(),
expected: brightness,
);
checkPropertyMatch(
name: kLocalizations,
actual: item.getFirstField(kLocalizations)?.toFunctionValue2()?.displayName,
actual: item.getFirstField(kLocalizations)?.toFunctionValue()?.displayName,
expected: localizations,
);
return matches;

View File

@ -335,6 +335,8 @@ List<_i1.WidgetPreview> previews() => [
_i2.buildWidgetPreview(
packageName: 'flutter_project',
scriptUri: 'STRIPPED',
line: 4,
column: 1,
previewFunction: () => _i3.preview(),
transformedPreview: const _i4.Preview(name: 'preview').transform(),
)

View File

@ -593,6 +593,7 @@ Review licenses that have not been accepted (y/N)?
);
});
// Warning test not available when minimum and error are aligned.
testUsingContext('detects minimum required java version', () async {
// Test with older version of JDK
final Platform platform = FakePlatform()
@ -636,49 +637,6 @@ Review licenses that have not been accepted (y/N)?
);
});
testUsingContext('detects minimum recommended java version', () async {
// Test with older version of JDK
final Platform platform = FakePlatform()
..environment = <String, String>{
'HOME': '/home/me',
Java.javaHomeEnvironmentVariable: 'home/java',
'PATH': '',
};
final sdkVersion = FakeAndroidSdkVersion()
..sdkLevel = gradle_utils.compileSdkVersionInt
..buildToolsVersion = gradle_utils.minBuildToolsVersion;
// Mock a pass through scenario to reach _checkJavaVersion()
sdk
..licensesAvailable = true
..platformToolsAvailable = true
..cmdlineToolsAvailable = true
..directory = fileSystem.directory('/foo/bar')
..sdkManagerPath = '/foo/bar/sdkmanager'
..emulatorPath = 'path/to/emulator';
sdk.latestVersion = sdkVersion;
const javaVersionText = 'openjdk version "16.0.1"';
final String errorMessage = UserMessages().androidJavaMinimumVersion(javaVersionText);
final ValidationResult validationResult = await AndroidValidator(
java: FakeJava(version: const Version.withText(16, 0, 1, javaVersionText)),
androidSdk: sdk,
logger: logger,
platform: platform,
userMessages: UserMessages(),
processManager: processManager,
).validate();
expect(validationResult.type, ValidationType.success);
expect(validationResult.messages.last.message, errorMessage);
expect(
validationResult.messages.any(
(ValidationMessage message) => message.message.contains('Unable to locate Android SDK'),
),
false,
);
});
testWithoutContext('Mentions `flutter config --android-sdk if user has no AndroidSdk`', () async {
final ValidationResult validationResult = await AndroidValidator(
java: FakeJava(),

View File

@ -334,7 +334,7 @@ void main() {
nativeAssets,
allOf(<Matcher>[
_onChannelIs('master', available: true, enabledByDefault: true),
_onChannelIs('stable', available: false, enabledByDefault: false),
_onChannelIs('stable', available: true, enabledByDefault: true),
_onChannelIs('beta', available: true, enabledByDefault: true),
]),
);

View File

@ -9,6 +9,8 @@ import 'package:widget_preview_scaffold/src/widget_preview.dart';
Iterable<WidgetPreview> buildMultiWidgetPreview({
required String packageName,
required String scriptUri,
required int line,
required int column,
required MultiPreview preview,
required Object? Function() previewFunction,
}) {
@ -16,6 +18,8 @@ Iterable<WidgetPreview> buildMultiWidgetPreview({
(p) => buildWidgetPreview(
packageName: packageName,
scriptUri: scriptUri,
line: line,
column: column,
transformedPreview: p,
previewFunction: previewFunction,
),
@ -25,6 +29,8 @@ Iterable<WidgetPreview> buildMultiWidgetPreview({
WidgetPreview buildWidgetPreview({
required String packageName,
required String scriptUri,
required int line,
required int column,
required Preview transformedPreview,
required Object? Function() previewFunction,
}) {
@ -39,6 +45,8 @@ WidgetPreview buildWidgetPreview({
return WidgetPreview(
builder: previewBuilder,
scriptUri: scriptUri,
line: line,
column: column,
previewData: transformedPreview,
packageName: packageName,
);
@ -47,6 +55,8 @@ WidgetPreview buildWidgetPreview({
WidgetPreview buildWidgetPreviewError({
required String packageName,
required String scriptUri,
required int line,
required int column,
required String packageUri,
required String functionName,
required bool dependencyHasErrors,
@ -58,6 +68,8 @@ WidgetPreview buildWidgetPreviewError({
return WidgetPreview(
builder: () => Text('$functionName: $errorMessage'),
scriptUri: scriptUri,
line: line,
column: column,
previewData: const Preview(group: 'Invalid Previews'),
packageName: packageName,
);

View File

@ -31,15 +31,33 @@ class WidgetPreview {
const WidgetPreview({
required this.builder,
required this.scriptUri,
required this.line,
required this.column,
required this.previewData,
required this.packageName,
});
@visibleForTesting
const WidgetPreview.test({
required this.builder,
required this.previewData,
this.scriptUri = '',
this.line = -1,
this.column = -1,
this.packageName = '',
});
/// The absolute file:// URI pointing to the script containing this preview.
///
/// This matches the URI format sent by IDEs for active location change events.
final String scriptUri;
/// The line at which the Preview annotation was applied.
final int line;
/// The column at which the Preview annotation was applied.
final int column;
/// The name of the package in which a preview was defined.
///
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
@ -104,6 +122,7 @@ class WidgetPreview {
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty<String>('name', name, ifNull: 'not set'))
..add(DiagnosticsProperty<String>('group', previewData.group))
..add(DiagnosticsProperty<Size>('size', size))
..add(DiagnosticsProperty<double>('textScaleFactor', textScaleFactor))
..add(DiagnosticsProperty<PreviewThemeData>('theme', theme))

View File

@ -178,12 +178,16 @@ class NoPreviewsDetectedWidget extends StatelessWidget {
}
}
/// A wrapper that serves as the root entry for a single preview in the widget inspector.
class PreviewWidget extends StatelessWidget {
const PreviewWidget({super.key, required this.preview, required this.child});
final WidgetPreview preview;
final Widget child;
@override
StatelessElement createElement() => PreviewWidgetElement(this);
@override
Widget build(BuildContext context) {
return child;
@ -191,7 +195,9 @@ class PreviewWidget extends StatelessWidget {
@override
String toStringShort() {
final StringBuffer buffer = StringBuffer('@Preview');
final StringBuffer buffer = StringBuffer(
'@${preview.previewData.runtimeType}',
);
if (preview.name != null) {
buffer.write('(name: "${preview.name}")');
}
@ -205,6 +211,12 @@ class PreviewWidget extends StatelessWidget {
}
}
/// A custom [StatelessElement] with the sole purpose of simplifying identifying
/// selections of @Preview annotations in the widget inspector.
class PreviewWidgetElement extends StatelessElement {
PreviewWidgetElement(super.widget);
}
class WidgetPreviewGroupWidget extends StatelessWidget {
const WidgetPreviewGroupWidget({
super.key,

View File

@ -3,7 +3,10 @@
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart' as path;
import 'package:widget_preview_scaffold/src/dtd/editor_service.dart';
import 'package:widget_preview_scaffold/src/widget_preview_rendering.dart';
import 'dtd/dtd_services.dart';
import 'widget_preview.dart';
@ -21,7 +24,11 @@ class WidgetPreviewScaffoldController {
required PreviewsCallback previews,
@visibleForTesting WidgetPreviewScaffoldDtdServices? dtdServicesOverride,
}) : _previews = previews,
dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices();
dtdServices = dtdServicesOverride ?? WidgetPreviewScaffoldDtdServices() {
// Overrides the default WidgetInspectorService instance to handle selection
// events.
_WidgetPreviewScaffoldInspectorService(dtdServices: dtdServices);
}
/// Initializes the controller by establishing a connection to DTD and
/// listening for events.
@ -154,3 +161,77 @@ class WidgetPreviewScaffoldController {
}
}
}
/// A custom [WidgetInspectorService] responsible for routing navigation events
/// to the IDE.
class _WidgetPreviewScaffoldInspectorService with WidgetInspectorService {
_WidgetPreviewScaffoldInspectorService({required this.dtdServices}) {
WidgetInspectorService.instance = this;
}
final WidgetPreviewScaffoldDtdServices dtdServices;
// Keys used to specify the creation location of a widget when serializing a
// DiagnosticsNode to JSON. This location is used by the widget inspector
// to jump to the creation location of a selected widget.
static const kFile = 'fileUri';
static const kLine = 'line';
static const kColumn = 'column';
CodeLocation? _nextNavigationLocation;
@protected
@override
bool setSelection(Object? object, [String? groupName]) {
// The next navigation event sent to `postEvent` will be for this selection.
// Save the location of preview annotation applications so we can override
// the navigation target in `postEvent`.
if (object is PreviewWidgetElement) {
final previewData = (object.widget as PreviewWidget).preview;
_nextNavigationLocation = CodeLocation(
uri: previewData.scriptUri,
line: previewData.line,
column: previewData.column,
);
}
final result = super.setSelection(object, groupName);
_nextNavigationLocation = null;
return result;
}
@override
void postEvent(
String eventKind,
Map<Object, Object?> eventData, {
String stream = 'Extension',
}) {
// It's unlikely that the widget previewer will be connected to directly by
// an IDE via the VM service, so we forward navigation events via the
// Editor DTD service.
if (eventKind == 'navigate') {
CodeLocation? location = _nextNavigationLocation;
if (eventData case {
kFile: final String file,
kLine: final int line,
kColumn: final int column,
} when location == null) {
location = CodeLocation(uri: file, line: line, column: column);
} else if (location != null) {
// If a [PreviewWidgetElement] was selected, we're not navigating to the
// creation location of the widget. Override the location details in the
// event data, just in case an IDE is attached and listening for
// navigation events through the VM service.
// TODO(bkonyi): determine if this is necessary
eventData.addAll(<String, Object>{
kFile: location.uri,
kLine: location.line!,
kColumn: location.column!,
});
}
if (location != null) {
dtdServices.navigateToCode(location);
}
}
super.postEvent(eventKind, eventData, stream: stream);
}
}

View File

@ -71,6 +71,8 @@ WidgetPreviewerWidgetScaffolding previewsForCustomMultiPreview() {
scriptUri: '',
preview: BrightnessPreview(name: 'MyPreview'),
previewFunction: () => Text('Foo'),
line: -1,
column: -1,
);
final controller = FakeWidgetPreviewScaffoldController();
return WidgetPreviewerWidgetScaffolding(

View File

@ -42,11 +42,9 @@ void main() {
final controller = WidgetPreviewScaffoldController(
dtdServicesOverride: fakeDtdServices,
previews: () => [
WidgetPreview(
WidgetPreview.test(
builder: () => throw Exception('Error!'),
scriptUri: '',
previewData: Preview(),
packageName: '',
),
],
);

View File

@ -29,17 +29,15 @@ Future<void> testImpl({
isWindows: isWindows,
);
final previews = <WidgetPreview>[
WidgetPreview(
WidgetPreview.test(
builder: () => Text('widget1'),
scriptUri: script1Uri.toString(),
previewData: Preview(group: 'group'),
packageName: '',
),
WidgetPreview(
WidgetPreview.test(
builder: () => Text('widget2'),
scriptUri: script2Uri.toString(),
previewData: Preview(group: 'group'),
packageName: '',
),
];
final controller = FakeWidgetPreviewScaffoldController(
@ -189,17 +187,13 @@ void main() {
) async {
final dtdServices = FakeWidgetPreviewScaffoldDtdServices();
final previews = <WidgetPreview>[
WidgetPreview(
WidgetPreview.test(
builder: () => Text('widget1'),
scriptUri: '',
previewData: Preview(group: 'group'),
packageName: '',
),
WidgetPreview(
WidgetPreview.test(
builder: () => Text('widget2'),
scriptUri: '',
previewData: Preview(group: 'group'),
packageName: '',
),
];
final controller = FakeWidgetPreviewScaffoldController(

View File

@ -37,11 +37,9 @@ WidgetPreviewerWidgetScaffolding previewForLocalizations({
return WidgetPreviewerWidgetScaffolding(
child: WidgetPreviewWidget(
controller: controller,
preview: WidgetPreview(
scriptUri: '',
preview: WidgetPreview.test(
builder: () => Text('Foo', key: key),
previewData: Preview(localizations: previewLocalizationsData),
packageName: '',
),
),
);

View File

@ -50,6 +50,8 @@ void main() {
currentPreviews.add(
WidgetPreview(
scriptUri: '',
line: -1,
column: -1,
builder: () => const Text('Foo'),
previewData: Preview(),
packageName: '',

Some files were not shown because too many files have changed in this diff Show More