Reputation: 285
This code was working just fine a while ago, but is now misbehaving for no reasons, I tried to re-install the app 2 times, but didn't worked, what might be causing it? It was giving me a list of available cameras before, but after a hot-restart, the code is constantly breaking.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras(); // returns an empty list, which it shouldn't because I'm using a real device which has two physical cameras, all dependencies are added, all permissions are allowed.
runApp(
MyApp(),
);
}
Note: The error is coming when I try to access the cameras list, but it was able to access it two hours ago, why is it returning an empty list right now?
Upvotes: 0
Views: 2317
Reputation: 66
For all of you that may have done the same error as me by copy-pasting "camera" code from pubdev, keep in mind that the code of "camera" was made for being main page, wich means _cameras is initialised by :
List<CameraDescription> _cameras = <CameraDescription>[];
but it's the main() function role to fill it, so if you call CameraApp() from outside of the page, main will not be triggered, therefore you need to modify the class like this:
class CameraApp extends StatelessWidget {
/// Default Constructor
const CameraApp({Key? key, required this.cameras}) : super(key: key);
final List<CameraDescription> cameras;
@override
Widget build(BuildContext context) {
_cameras=cameras;
return const MaterialApp(
home: CameraExampleHome(),
);
}
}
and call it from another page with:
await availableCameras().then((value) => Navigator.push(context,
MaterialPageRoute(builder: (_) => CameraApp(cameras: value))));
Like so the cameras are properly filled. That's my working solution. Possible amelioration: Maybe the cameras list could be filled directly in CameraApp?
Upvotes: 2
Reputation: 285
This error is most probably due to the "camera" plugin's internal working or due to Android OS's security reasons or something like that. The camera package is new, so you can expect such behaviors, but there are bunch of other enhanced packages as well based on the original one. In my case, I used "flutter_camera" and modified the source code as per my needs in order to achieve the desired UI, and it works pretty good.
Update: I found out that the error was indirectly connected to "compileSdkVersion" in my app/build.gradle being set to 33 which was required by a random flutter plugin, setting it to 29 allowed me to access my camera and successfully executed availableCameras() method too but then the plugin can't be used.
Upvotes: 0