Skip to content

Commit 956ba9e

Browse files
authored
[camera_web] Fix TypeError when reading the torch capability (#12647)
## What broke `setFlashMode` and `takePicture` threw on any camera that has a flash. The Image Capture specification declares `sequence<boolean> torch` in `MediaTrackCapabilities`. `package:web` is generated from that specification, so `torchNullable` was typed `JSArray<JSBoolean>?`. No browser ships that shape. Chromium and WebKit both declare a bare `boolean torch`. Reading the property threw before the torch could be applied. The error depends on the compiler: | Compiler | Error | | --- | --- | | DDC | `TypeError: true: type 'bool' is not a subtype of type 'JSArray<Object?>?'` | | dart2js | `NoSuchMethodError: method not found: 'gq'` | | dart2wasm | `ArgumentError: Invalid argument(s)` | The same line held two more defects: - `.first` gave the wrong answer for `[false, true]`. A specification-shaped sequence lists the values the source accepts, so that means the torch can be turned on. - `.first` threw `StateError` on an empty sequence. ## The fix Read `torch` as `JSAny?` and add `canEnableTorch`, which accepts either shape and returns false for anything else. A sequence is answered with `any` instead of `first`, and is only trusted when every element is a boolean. Anything unrecognised raises `torchModeNotSupported` instead of crashing, and prints a debug-only warning so the shape can be reported. ## Test matrix | Browser reports | Before | After | | --- | --- | --- | | `true` | TypeError | torch on | | `false` | TypeError | torchModeNotSupported | | `[false, true]` | wrong answer | torch on | | `[true]` | torch on | torch on | | `[false]` | torchModeNotSupported | torchModeNotSupported | | `[]` | StateError | torchModeNotSupported | | key absent | torchModeNotSupported | torchModeNotSupported | | `'yes'` | TypeError | torchModeNotSupported + warning | | `['yes']` | TypeError | torchModeNotSupported + warning | Nine cases are covered by integration tests. Six of them fail without this change. ## Devices tested All nine shapes were run through the real plugin code on each of these. All passed. | Device | Browser | Result | | --- | --- | --- | | Moto G56 5G, Android 16 | Chrome 151 | 9 / 9 | | macOS 26.3 | Safari 26.3 | 9 / 9 | | iPhone 17 Pro simulator, iOS 26.1 | Safari | 9 / 9 | | macOS 26.3 | Chrome 151, dart2js and dart2wasm | 9 / 9 | On the Moto G56 the rear camera reports `torch: true` as a bare boolean, and the flash now turns on. The front camera does not report the key at all and raises `torchModeNotSupported` as expected. ## What was added - `canEnableTorch` on `NonStandardFieldsOnMediaTrackCapabilities`, which reads either shape. - A debug-only `debugPrint` warning for a shape that is neither, so an unknown browser can be reported rather than failing quietly. - Nine integration tests covering every shape, plus a check that a recognised shape never warns. - A CHANGELOG entry and a version bump to `0.3.5+6`. ## What was removed - The `JSArray<JSBoolean>?` type on `torchNullable`, which no browser matches. - The `?.toDart.first.toDart ?? false` chain in `_setTorchMode`. ## Issues fixed by this PR Fixes flutter/flutter#191384 ## Pre-Review Checklist 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent e2aa2ea commit 956ba9e

5 files changed

Lines changed: 178 additions & 5 deletions

File tree

‎packages/camera/camera_web/CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
## 0.3.5+6
2+
3+
* Fixes a `TypeError` in `setFlashMode` and `takePicture` caused by browsers reporting the
4+
`torch` capability as a `boolean` instead of the `boolean` sequence the Image Capture
5+
specification describes.
6+
17
## 0.3.5+5
28

39
* Removes invalid @JS annotation from extension type constructors.

‎packages/camera/camera_web/example/integration_test/camera_test.dart‎

Lines changed: 135 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import 'package:camera_platform_interface/camera_platform_interface.dart';
1212
// ignore_for_file: implementation_imports
1313
import 'package:camera_web/src/camera.dart';
1414
import 'package:camera_web/src/types/types.dart';
15+
import 'package:flutter/foundation.dart';
1516
import 'package:flutter_test/flutter_test.dart';
1617
import 'package:integration_test/integration_test.dart';
1718
import 'package:mockito/mockito.dart';
@@ -262,7 +263,7 @@ void main() {
262263
videoElement = getVideoElementWithBlankStream(const Size(100, 100))..muted = true;
263264

264265
mockVideoTrack.getCapabilities = () {
265-
return MediaTrackCapabilities(torch: <JSBoolean>[true.toJS].toJS);
266+
return capabilitiesWithTorch(true.toJS);
266267
}.toJS;
267268
});
268269

@@ -443,6 +444,125 @@ void main() {
443444
expect(capturedConstraints[0].torch.dartify(), false);
444445
});
445446

447+
// Regression tests for https://github.com/flutter/flutter/issues/191384.
448+
group('reads the torch capability', () {
449+
late List<String> warnings;
450+
late DebugPrintCallback originalDebugPrint;
451+
452+
setUp(() {
453+
warnings = <String>[];
454+
originalDebugPrint = debugPrint;
455+
debugPrint = (String? message, {int? wrapWidth}) {
456+
if (message != null) {
457+
warnings.add(message);
458+
}
459+
};
460+
});
461+
462+
tearDown(() {
463+
debugPrint = originalDebugPrint;
464+
});
465+
466+
final torchCapabilities = <String, (JSAny?, bool)>{
467+
'reported as a bare true by Chromium and WebKit': (true.toJS, true),
468+
'reported as a bare false by Chromium and WebKit': (false.toJS, false),
469+
'reported as a sequence by a browser following the specification': (
470+
<JSBoolean>[false.toJS, true.toJS].toJS,
471+
true,
472+
),
473+
'reported as a sequence holding only true': (<JSBoolean>[true.toJS].toJS, true),
474+
'reported as a sequence holding only false': (<JSBoolean>[false.toJS].toJS, false),
475+
'reported as an empty sequence': (<JSBoolean>[].toJS, false),
476+
'not reported by the browser at all': (null, false),
477+
};
478+
479+
for (final MapEntry<String, (JSAny?, bool)> testCase in torchCapabilities.entries) {
480+
final (JSAny? capability, bool canEnableTorch) = testCase.value;
481+
482+
testWidgets(testCase.key, (WidgetTester tester) async {
483+
mockMediaDevices.getSupportedConstraints = () {
484+
return MediaTrackSupportedConstraints(torch: true);
485+
}.toJS;
486+
487+
mockVideoTrack.getCapabilities = () {
488+
return capabilitiesWithTorch(capability);
489+
}.toJS;
490+
491+
final camera = Camera(textureId: textureId, cameraService: cameraService)
492+
..window = window
493+
..stream = videoStream;
494+
495+
final capturedConstraints = <MediaTrackConstraints>[];
496+
mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) {
497+
if (constraints != null) {
498+
capturedConstraints.add(constraints);
499+
}
500+
return Future<JSAny?>.value().toJS;
501+
}.toJS;
502+
503+
if (canEnableTorch) {
504+
camera.setFlashMode(FlashMode.torch);
505+
506+
expect(capturedConstraints.length, 1);
507+
expect(capturedConstraints[0].torch.dartify(), true);
508+
} else {
509+
expect(
510+
() => camera.setFlashMode(FlashMode.torch),
511+
throwsA(
512+
isA<CameraWebException>()
513+
.having((CameraWebException e) => e.cameraId, 'cameraId', textureId)
514+
.having(
515+
(CameraWebException e) => e.code,
516+
'code',
517+
CameraErrorCode.torchModeNotSupported,
518+
),
519+
),
520+
);
521+
expect(capturedConstraints, isEmpty);
522+
}
523+
524+
expect(warnings, isEmpty, reason: 'a recognized shape must not warn');
525+
});
526+
}
527+
528+
final unrecognizedCapabilities = <String, JSAny>{
529+
'a value that is not a boolean': 'yes'.toJS,
530+
'a sequence holding something other than booleans': <JSAny>['yes'.toJS].toJS,
531+
};
532+
533+
for (final MapEntry<String, JSAny> testCase in unrecognizedCapabilities.entries) {
534+
testWidgets('warns while debugging when the browser reports '
535+
'${testCase.key}', (WidgetTester tester) async {
536+
mockMediaDevices.getSupportedConstraints = () {
537+
return MediaTrackSupportedConstraints(torch: true);
538+
}.toJS;
539+
540+
mockVideoTrack.getCapabilities = () {
541+
return capabilitiesWithTorch(testCase.value);
542+
}.toJS;
543+
544+
final camera = Camera(textureId: textureId, cameraService: cameraService)
545+
..window = window
546+
..stream = videoStream;
547+
548+
expect(
549+
() => camera.setFlashMode(FlashMode.torch),
550+
throwsA(
551+
isA<CameraWebException>().having(
552+
(CameraWebException e) => e.code,
553+
'code',
554+
CameraErrorCode.torchModeNotSupported,
555+
),
556+
),
557+
);
558+
559+
expect(warnings, hasLength(1));
560+
expect(warnings.single, contains('torch'));
561+
expect(warnings.single, contains('github.com/flutter/flutter/issues'));
562+
});
563+
}
564+
});
565+
446566
group('throws a CameraWebException', () {
447567
testWidgets('with torchModeNotSupported error '
448568
'when the torch mode is not supported '
@@ -1275,3 +1395,17 @@ void main() {
12751395
});
12761396
});
12771397
}
1398+
1399+
/// Builds a [MediaTrackCapabilities] reporting [torch] as its torch
1400+
/// capability, or omitting the capability entirely when [torch] is null.
1401+
///
1402+
/// Browser engines disagree on the shape of this value, so it cannot be built
1403+
/// with the typed `MediaTrackCapabilities` constructor from `package:web`,
1404+
/// which only accepts the `sequence<boolean>` the specification describes.
1405+
MediaTrackCapabilities capabilitiesWithTorch(JSAny? torch) {
1406+
final capabilities = JSObject();
1407+
if (torch != null) {
1408+
capabilities.setProperty('torch'.toJS, torch);
1409+
}
1410+
return capabilities as MediaTrackCapabilities;
1411+
}

‎packages/camera/camera_web/lib/src/camera.dart‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,7 @@ class Camera {
333333

334334
if (videoTracks.isNotEmpty) {
335335
final web.MediaStreamTrack defaultVideoTrack = videoTracks.first;
336-
final bool canEnableTorchMode =
337-
defaultVideoTrack.getCapabilities().torchNullable?.toDart.first.toDart ?? false;
336+
final bool canEnableTorchMode = defaultVideoTrack.getCapabilities().canEnableTorch;
338337

339338
if (canEnableTorchMode) {
340339
defaultVideoTrack.applyWebTweakConstraints(

‎packages/camera/camera_web/lib/src/pkg_web_tweaks.dart‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import 'dart:js_interop';
88

9+
import 'package:flutter/foundation.dart';
910
import 'package:web/web.dart';
1011

1112
/// Adds missing fields to [Element].
@@ -28,8 +29,41 @@ extension NonStandardFieldsOnMediaTrackCapabilities on MediaTrackCapabilities {
2829
@JS('zoom')
2930
external WebTweakMediaSettingsRange? get zoomNullable;
3031

32+
/// The raw `torch` capability, as reported by the browser.
33+
///
34+
/// Chromium and WebKit report a `boolean`, while the Image Capture
35+
/// specification changed this to `sequence<boolean>` in
36+
/// https://github.com/w3c/mediacapture-image/pull/305. Typed as [JSAny] so
37+
/// that either shape can be read; see [canEnableTorch].
3138
@JS('torch')
32-
external JSArray<JSBoolean>? get torchNullable;
39+
external JSAny? get torchNullable;
40+
41+
/// Whether the camera is able to turn its torch on.
42+
bool get canEnableTorch {
43+
final JSAny? torch = torchNullable;
44+
if (torch == null) {
45+
return false;
46+
}
47+
if (torch.isA<JSBoolean>()) {
48+
return (torch as JSBoolean).toDart;
49+
}
50+
if (torch.isA<JSArray<JSAny?>>()) {
51+
final List<JSAny?> values = (torch as JSArray<JSAny?>).toDart;
52+
if (values.every((JSAny? value) => value.isA<JSBoolean>())) {
53+
return values.any((JSAny? value) => (value! as JSBoolean).toDart);
54+
}
55+
}
56+
assert(() {
57+
debugPrint(
58+
'camera_web: ignoring the `torch` capability of this camera because '
59+
'the browser reported it as neither a boolean nor a sequence of '
60+
'booleans. Please report the browser and its version at '
61+
'https://github.com/flutter/flutter/issues.',
62+
);
63+
return true;
64+
}());
65+
return false;
66+
}
3367

3468
@JS('facingMode')
3569
external JSArray<JSString>? get facingModeNullable;

‎packages/camera/camera_web/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: camera_web
22
description: A Flutter plugin for getting information about and controlling the camera on Web.
33
repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_web
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
5-
version: 0.3.5+5
5+
version: 0.3.5+6
66

77
environment:
88
sdk: ^3.10.0

0 commit comments

Comments
 (0)