I have used stackoverflow for years but never bothered to register myself, but I feel the time has finally come. :)
I'm currently doing a school project in Flutter, which I'm very new to, and have now stumbled upon a problem. Have tried various things but I keep getting this exception:
The following LateError was thrown building Home(dirty, state: _HomeState#9ab2f):
LateInitializationError: Field '_image@17109416' has not been initialized.
What could be causing this issue? Here is my code:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MaterialApp(
home: Home(),
// debugShowCheckedModeBanner: false, // Turns off the 'DEBUG' sign in the upper right corner
));
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
// Camera implementation
late File _image;
final ImagePicker _picker = ImagePicker();
Future getImage() async {
final image = await _picker.pickImage(source: ImageSource.camera);
setState(() {
_image = File(image!.path);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 90,
title: const Text(
'School project',
style: TextStyle(
fontSize: 25.0,
//fontFamily: '', // change the font?
),
),
centerTitle: true,
backgroundColor: Colors.green[600],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Write or scan',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
)
),
const SizedBox(height: 50.0),
ElevatedButton.icon(
onPressed: () {
print('write'); // test
},
icon: const Icon(Icons.person_add_alt_rounded),
label: const Text('Write'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
),
const SizedBox(height: 15.0),
_image == null ? Text("No Image Selected") : Image.file(_image),
ElevatedButton.icon(
onPressed: () {
getImage;
print('camera'); // test
},
icon: const Icon(Icons.camera_alt_rounded),
label: const Text('Scan'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
)
]
),
),
);
}
}
Also, should I try and change the position of the
_image == null ? Text("No Image Selected") : Image.file(_image),
line somewhere more fitting or is it okay to have it nested like that? Do you have any other remarks on my code?
CodePudding user response:
try with this
ElevatedButton.icon(
onPressed: getImage, // here need to change
icon: const Icon(Icons.camera_alt_rounded),
label: const Text('Scan'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green[500]),
textStyle: MaterialStateProperty.all(TextStyle(fontSize: 22)),
)
)