LateError (LateInitializationError: Field 'image' has not been initialized.) - flutter

I'm making an application to hide messages in pictures,
everything is running smoothly and i have declared everything, but there is a problem i'm having "LateError (LateInitializationError: Field 'image' has not been initialized.)". can anyone help me?
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:hideimage/action/decode_req.dart';
import 'package:hideimage/action/encode_req.dart';
import 'package:hideimage/fight/decode.dart';
import 'package:hideimage/fight/encode.dart';
import 'package:image_picker/image_picker.dart';
class HomeScreen extends StatefulWidget {
HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final picker = ImagePicker();
late Uint8List image;
String text = "Example";
bool isLoading = false;
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
if (pickedFile != null) {
setState(() {
isLoading = true;
});
File _image = File(pickedFile.path);
EncodeRequest request =
EncodeRequest(_image.readAsBytesSync(), "", key: "");
image = await encodeMessageIntoImageAsync(request);
setState(() {
isLoading = false;
});
} else {
print('No Image Selected');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(text),
),
body: Center(
child: isLoading
? CircularProgressIndicator()
: image != null
? Text('No Image Selected')
: GestureDetector(
child: Image.memory(image),
onTap: () async {
setState(() {
isLoading = true;
});
DecodeRequest request = DecodeRequest(image, key: "");
text = await decodeMessageFromImageAsync(request);
setState(() {
isLoading = false;
});
},
)
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}

you have a misunderstanding, late variables are not nullable, you are only telling the compiler that you will assign its value later but still before using it.
here you are checking if image != null so image has not been initialized yet, thus you get this error.
what you need here is making image nullable not late
i.e change the declaration to this
Uint8List? image;

Related

Error :The argument type 'XFile' can't be assigned to the parameter type 'File'

I am working on a Flutter app to take image from gallery and predict the appropriate output via detection using the model I trained using Machine learning but, I am getting an error for this following code:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late bool _isLoading;
late File _image;
late List _output;
#override
void initState() {
// TODO: implement initState
super.initState();
_isLoading = true;
loadMLModel().then((value){
setState(() {
_isLoading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Brain Tumor Detection"),
),
body: _isLoading ? Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
) : SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_image == null ? Container() : Image.file(File(_image.path)),
SizedBox(height: 16,),
_output == null ? Text(""): Text(
"${_output[0]["label"]}"
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
chooseImage();
},
child: Icon(
Icons.image
),
)
,
);
}
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = image as File;
});
runModelOnImage(image);
}
runModelOnImage(File image) async{
var output = await Tflite.runModelOnImage(
path: image.path,
numResults: 2,
imageMean: 127.5,
imageStd: 127.5,
threshold: 0.5
);
setState(() {
_isLoading = false;
_output = output!;
});
}
loadMLModel() async {
await Tflite.loadModel(
model: "assets/btc.tflite",
labels: "assets/labels.txt"
);
}
}
The error is:
The argument type 'XFile' can't be assigned to the parameter type 'File'.
I have tried all the other alternatives given out there for imagepicker issues faced by other people. Any help to solve this would be great!
Thank you in advance!!
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = File(image.path);
});
runModelOnImage(_image);
}
I was facing the same issue. What I did was:
Created a variable of XFile in my widget XFile? _image;
Look at this function
Future getImageFromGallery() async {
_image = await ImagePicker()
.pickImage(source: ImageSource.gallery, maxHeight: 300, maxWidth: 300);
if (_image!.path.isNotEmpty) {
setState(() {
pickedImage = true;
});
}
}
On the press of a button, called the above function.
Used the follwing function to upload file on Firebase storage
Future uploadLogo(BuildContext? context, XFile? image) async {
FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage
.ref()
.child('shops/${_name.text}/Logo${DateTime.now().toString()}');
final path = image!.path; //Getting the path of XFile
File file = File(path);// Turning that into File
UploadTask uploadTask = ref
.putFile(file); //Getting a proper reference to upload on storage
final TaskSnapshot downloadUrl = (await uploadTask); //Uploading to //storage
imageUrlShop = await downloadUrl.ref.getDownloadURL();
}
My answer is almost same as of the earlier ones but there is a little change in the format and how the argument is being passed. This is working for me. Might work for you too...
You are calling runModelOnImage which takes a File as an argument, with an XFile.
chooseImage() async {
final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return null;
setState(() {
_isLoading = true;
_image = File(image.path);
});
runModelOnImage(_image);
}

flutter) There's a problem with using imagePicker

I'm using sdk 2.12.0 and image_picker 0.8.4 version.
I'm going to link my gallery to get an image.
However, when I press the Add Image button on my app, the app turns off immediately.
This is the code for the image_picker I used.
class CreatePage extends StatefulWidget {
const CreatePage({Key? key, required this.user}) : super(key: key);
final User user;
#override
_CreatePageState createState() => _CreatePageState();
}
class _CreatePageState extends State<CreatePage> {
//ImagePicker
final ImagePicker _picker = ImagePicker();
File? _imageFile;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
backgroundColor: Colors.blue,
child: Icon(Icons.add_a_photo),
),
);
}
Future<void> _getImage() async {
//ImagePiker
var image = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
_imageFile = File(image!.path);
});
}
And this is my full code about this page. (Firebase code is included)
import 'dart:io';
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class CreatePage extends StatefulWidget {
//user info
const CreatePage({Key? key, required this.user}) : super(key: key);
final User user;
#override
_CreatePageState createState() => _CreatePageState();
}
class _CreatePageState extends State<CreatePage> {
//input text
final TextEditingController createText = TextEditingController();
//ImagePicker
final ImagePicker _picker = ImagePicker();
File? _imageFile;
//_createPageState가 제거될 때 호출됨
#override
void dispose() {
// TODO: implement dispose
createText.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: _getImage,
backgroundColor: Colors.blue,
child: Icon(Icons.add_a_photo),
),
);
}
_buildAppbar() {
return AppBar(
actions: [
IconButton(
icon: Icon(Icons.send),
onPressed: () {
_uploadPost(context);
},
),
],
);
}
_buildBody() {
return SingleChildScrollView(
child: Column(
children: [
_imageFile == null ? Text("No Image") : Image.file(_imageFile!),
TextField(
controller: createText,
decoration: InputDecoration(
hintText: "내용을 입력하세요",
),
)
],
),
);
}
//gallery image
Future<void> _getImage() async {
var image = await _picker.pickImage(source: ImageSource.gallery);
setState(() {
_imageFile = File(image!.path);
});
}
Future _uploadPost(BuildContext context) async {
final firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('post')
.child('${DateTime.now().microsecondsSinceEpoch}.png');
final task = await firebaseStorageRef.putFile(
_imageFile!, SettableMetadata(contentType: "image/png")
);
final uri = await task.ref.getDownloadURL();
//database document
final doc = FirebaseFirestore.instance.collection('post').doc();
//json type
await doc.set({
'id': doc.id,
'photoUrl': uri.toString(), //storage file url
'contents': createText, //user input text
'email': widget.user.email, //user email
'displayName': widget.user.displayName, //user name
'userPhotoUrl': widget.user.photoURL, //user profile image
});
//return page
Navigator.pop(context);
}
}
Pressing the floatingActionButton turns off the app and outputs the following error.
Lost connection to device.
May I know the cause of this?
Thank you in advance.
try adding dependency
image_picker: ^0.8.3+2
import 'package:image_picker/image_picker.dart';
then add this code
String url = "";
ImagePicker image = ImagePicker();
File ? file;
getImage() async {
var img = await image.pickImage(source: ImageSource.gallery);
setState(() {
file = File(img!.path);
});
}
And add:
onTap: () {
getImage();
},
add code:
child: file != null ?
Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
color: Colors.black,
margin: EdgeInsets.only(top: 80),
width: double.infinity,
height: 250,
child: Image.file(
file!,
fit: BoxFit.contain,
),
),
),
My guess is that you don't have permission to access the Media on the device, thus aborting the app the moment you try to do so. Check out the permission handler package.

Flutter tflite image classification how to not show wrong results

Im trying to understand tensorflow and I wanted to create a flutter app with Image Classification for cat or dog.
I used https://teachablemachine.withgoogle.com/ to train my model with 100 epoches and 128 batches. The ouput of my model is 97% accuracy for both the cat and dog. I used a dataset from kaggle with 4000 images for each cat and dog.
My Code:
import 'dart:io';
import 'package:tflite/tflite.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
File? _image;
bool _loading = false;
List<dynamic>? _output;
final _picker = ImagePicker();
pickImage() async {
var image = await _picker.getImage(source: ImageSource.camera);
if (image == null) {
return null;
}
setState(() {
_image = File(image.path);
});
classifyImage(_image);
}
pickGalleryImage() async {
var image = await _picker.getImage(source: ImageSource.gallery);
if (image == null) {
return null;
}
setState(() {
_image = File(image.path);
});
classifyImage(_image);
}
#override
void initState() {
super.initState();
_loading = true;
loadModel().then((value) {
// setState(() {});
});
}
#override
void dispose() {
Tflite.close();
super.dispose();
}
classifyImage(File? image) async {
var output = await Tflite.runModelOnImage(
path: image!.path,
numResults: 2,
threshold: 0.5,
imageMean: 127.5,
imageStd: 127.5,
);
setState(() {
_loading = false;
_output = output;
});
}
loadModel() async {
await Tflite.loadModel(
model: 'assets/model_unquant.tflite',
labels: 'assets/labels.txt',
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cat vs Dog Classifier'),
),
body: Center(
child: Column(
children: [
SizedBox(height: 160.0),
_image == null
? Text('No image selected')
: Container(
child: Image.file(_image!),
height: 250.0, // Fixed height for image
),
SizedBox(height: 20.0),
_output != null ? Text('${_output![0]['label']}') : Container(),
SizedBox(height: 50.0),
ElevatedButton(
onPressed: pickImage,
child: Text('Take Picture'),
),
ElevatedButton(
onPressed: pickGalleryImage,
child: Text('Camera Roll'),
),
],
),
),
);
}
}
My question:
If im picking a different image which isn't cat or dog, im still getting a 100% cat or dog feedback most of the time. How to not show these wrong results? What can we actually do?
You have to train Your original model on 3 classes:
cat
dog
other
then convert to tflite model and use it in your flutter project

error when using File with ImagePicker Flutter

The error is with this line: File selectedImage
I only have dart.io imported, not even dart.html so I'm not sure why I'm getting this error.
here is the longer piece of code
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:random_string/random_string.dart';
import 'package:tennis_event_app/services/crud.dart';
class CreateBlog extends StatefulWidget {
#override
_CreateBlogState createState() => _CreateBlogState();
}
class _CreateBlogState extends State<CreateBlog> {
late String pass, authorName, title, desc;
File selectedImage;
final picker = ImagePicker();
bool _isLoading = false;
CrudMethods crudMethods = new CrudMethods();
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
selectedImage = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
(this is not the entire code but just a larger piece)
What exact error are you getting?
Suggestion
Please do well to put setState((){...}); in the if-statement like this:
if(pickedFile != null){
setState((){
selectedImage = File(pickedFile.path);
});
}else{
print('No image selected');
}
and Hot Reload.
SEE COMPLETE SOLUTION THAT WORKED FOR ME
class _ImageSelectorState extends State<ImageSelector> {
var imageFile;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 200.0,
height: 200.0,
color: Colors.grey.shade300,
child: imageFile != null
? Image.file(imageFile)
: Icon(
Icons.image,
),
),
SizedBox(height: 20.0),
//Button
Center(
child: ElevatedButton(
onPressed: _pickImage,
child: Text('Upload Image'),
),
),
],
),
);
}
_pickImage() async {
try {
final picker = await ImagePicker().getImage(
source: ImageSource.gallery,
);
if (picker != null) {
setState(() {
imageFile = File(picker.path);
});
}
} catch (e) {
print(e);
}
}
}
Result
Solution I Used:
I ended up changing File selectedImage; to File ? selectedImage;

Cannot load image with flutter image_editor_pro

I want to use this package. But I seem to be missing something. This is my code:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File _image = File("assets/images/butterfly.jpg");
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
error: Cannot open file, path = 'assets/images/butterfly.jpg' (OS Error: No such file or directory, errno = 2).
How am I supposed to load an image with this?
I even tried to use Image from the get go. But no result. Maybe I am doing the File to Image conversion wrong?
**Update 1: **
class _HomePageState extends State<HomePage> {
final image = Image.asset('assets/images/butterfly.jpg');
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
image = geteditimage; // shows error asking to make the field not final
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () {
getimageditor();
},
).toCenter(),
isFalse: Image.file(image).toCenter()) //The argument type 'Image' can't be assigned to the parameter type 'File'.
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
You need to add your asset directories to your pubspec.yaml.
For example:
dependencies:
...
dev_dependencies:
...
flutter:
uses-material-design: true
assets:
- assets/
- assets/images/
Then you can read the file as an image like so:
final image = Image.asset('assets/images/butterfly.jpg');
If you need to read the image as a file for the package you are trying to use, instead of coding in images, use a package like image_picker.
For your case:
class _HomePageState extends State<HomePage> {
File _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() =>
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
);
})).then((geteditimage) {
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
#override
Widget build(BuildContext context) {
return condition(
condtion: _image == null,
isTue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse: Image.file(_image).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTextColorWhite().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red));
}
}
Widget condition({bool condtion, Widget isTue, Widget isFalse}) {
return condtion ? isTue : isFalse;
}
Solution for this is error is to prevent the Image.file to read from null by setting a null check:
_image == null ? Container() : Image.file(_image).toCenter())
The app will build without error, and after that you can use the image editor pro to edit your image.
If anyone wants to pass image to editor page from image picker :
make changes to image_editor_pro.dart file
final Color appBarColor;
final Color bottomBarColor;
final Directory pathSave;
final double pixelRatio;
final File image;
ImageEditorPro(
{this.appBarColor,
this.bottomBarColor,
this.pathSave,
this.pixelRatio,
this.image});
#override
void initState() {
timers();
_controller.clear();
type.clear();
// fontsize.clear();
offsets.clear();
// multiwidget.clear();
howmuchwidgetis = 0;
_image = widget.image;
super.initState();
}
**Then use this code **
import 'package:flutter/material.dart';
import 'dart:io';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_editor_pro/image_editor_pro.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:firexcode/firexcode.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:image_picker/image_picker.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return HomePage().xMaterialApp();
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
File? _image;
final picker = ImagePicker();
Future<void> getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
// ignore: unnecessary_null_comparison
if (pickedFile != null) {
_image = File(pickedFile.path);
print("images : $_image");
} else {
print('No image selected.');
}
});
}
Future<void> getimageditor() async {
// ignore: unused_local_variable
final geteditimage =
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ImageEditorPro(
appBarColor: Colors.blue,
bottomBarColor: Colors.blue,
image: _image,
);
})).then((geteditimage) {
print("image : $geteditimage");
if (geteditimage != null) {
setState(() {
_image = geteditimage;
});
}
}).catchError((er) {
print(er);
});
}
#override
Widget build(BuildContext context) {
return condition(
// ignore: unnecessary_null_comparison
condtion: _image == null,
isTrue: 'Open Editor'.text().xRaisedButton(
onPressed: () async {
await getImage();
await getimageditor();
},
).toCenter(),
isFalse:
// ignore: unnecessary_null_comparison
_image == null ? Container() : Image.file(_image!).toCenter())
.xScaffold(
appBar: 'Image Editor Pro example'.xTabText().xAppBar(),
floatingActionButton:
Icons.add.xIcons().xFloationActiobButton(color: Colors.red))
.xRaisedButton(onPressed: () {
getimageditor();
});
}
}
Widget? condition({required bool condtion, Widget? isTrue, Widget? isFalse}) {
return condtion ? isTrue : isFalse;
}