Flutter开启相机触发The method '[]' was called on null错误,求解决方案
Hey, let's break down what's going wrong here and fix it step by step!
The error The method '[]' was called on null happens because your global cameras variable is null when you try to access cameras[0] in the CameraTabPage state. You never actually initialized it with the list of available cameras from the device.
What's the root cause?
In your main.dart, the main() function immediately calls runApp(MyApp()) without fetching the camera list first. The availableCameras() method (from the camera package) is asynchronous, so you need to wait for it to complete before using the cameras variable.
How to fix this:
Initialize Flutter binding and fetch cameras first
Before launching your app, you need to make sure Flutter's binding is initialized (required for native plugin calls like camera access) and then wait foravailableCameras()to populate thecamerasvariable.Add error handling for edge cases
It's a good idea to handle scenarios where no cameras are available (like emulators without camera support) to prevent crashes.
Updated Code:
main.dart's main function:
Future<void> main() async { // Ensure Flutter's binding is initialized before plugin calls WidgetsFlutterBinding.ensureInitialized(); try { // Fetch the list of available cameras cameras = await availableCameras(); } on CameraException catch (e) { print("Failed to get cameras: ${e.description}"); cameras = []; } // Now launch the app with cameras initialized runApp(MyApp()); }
Optional: Add safety checks in camera.dart
To avoid crashes if cameras are still unavailable, add checks in your CameraTabPage state:
@override void initState() { super.initState(); if (cameras.isNotEmpty) { controller = CameraController(cameras[0], ResolutionPreset.medium); controller.initialize().then((_) { if (!mounted) return; setState(() {}); }); } } @override Widget build(BuildContext context) { if (cameras.isEmpty || (controller?.value.isInitialized != true)) { return const Center(child: Text("Could not access camera")); } return AspectRatio( aspectRatio: controller.value.aspectRatio, child: CameraPreview(controller), ); }
With these changes, the cameras variable will be properly populated before your app starts, and you'll no longer get that null error when trying to access the first camera.
内容的提问来源于stack exchange,提问作者Mohammad jayyousi

