i'm new at flutter and i want to implements camera to me app but i get some error "LateInitializationError: Field 'imgCamera' has not been initialized."
///main.dart
import 'package:flutter/material.dart';
import 'package:untitled/MySplashPage.dart';
import 'package:camera/camera.dart';
List<CameraDescription> cameras = <CameraDescription>[];
Future <void> main() async
{
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'detections image',
home: MySplashPage(),
);
}
}
and my home page the problem is at imgCamera
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'main.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isWorking = false;
String result="";
late CameraController cameraController;
late CameraImage imgCamera ;
final ButtonStyle flatButtonStyle = TextButton.styleFrom(
primary: Colors.white,
minimumSize: const Size(88, 44),
padding: const EdgeInsets.symmetric(horizontal: 16.0),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(2.0)),
),
backgroundColor: Colors.blue,
);
initCamera()
{
cameraController = CameraController(cameras[0], ResolutionPreset.medium);
cameraController.initialize().then((value) {
if(!mounted){
return;
}
setState(() {
cameraController.startImageStream((imageFromStream) => {
if(!isWorking){
isWorking = true,
imgCamera = imageFromStream,
}
});
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/ia2.jpeg")
),
),
child: Column(
children: [
Center(
child: Container(
height: 320,
width: 330,
child: Image.asset("assets/images/ia.jpeg"),
),
),
Center(
child: TextButton(
style: flatButtonStyle,
onPressed: () {
initCamera();
},
child: imgCamera == null
? const SizedBox(
height: 270 ,
width: 360,
child: Icon(Icons.photo_camera_front, color: Colors.blueAccent, size: 40,),
)
: AspectRatio(
aspectRatio: cameraController.value.aspectRatio,
child: CameraPreview(cameraController),
),
),
),
],
),
),
),
),
);
}
}
thank for your answers it will be very helpful i try to check on youtube but all that video it was for old version of flutter
I guess the error said it all, you try to use the uninitialized imgCamera == null
in your widget.
To make the code run before fixing others, try to make imgCamera
nullable and assign null
.
And then I think you don't need to initialize the controller everytime you want to launch the camera (onPressed
), since you use state, I think you can utilize the initState
function.