Minsaf
Minsaf

Reputation: 274

FLutter File initialization failed

I created an app to pick an image from the gallery and display it. I have created a File called "image" as mentioned below.

File image;

Then I created a function to pick the image as follow

void _pickImageCamera() async {
final picker = ImagePicker();
final pickedImage = await picker.getImage(source: ImageSource.gallery);
final pickedImageFile = File(image.path);
setState(() {
  image = pickedImageFile;
});

}

The app doesnt run and shows the following error

═══════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building Pick(dirty, state: _PickState#07f0f):
LateInitializationError: Field 'image' has not been initialized.

The relevant error-causing widget was
Pick
lib\main.dart:23
When the exception was thrown, this was the stack
#0      _PickState.image (package:clone_insta/Picker.dart)
package:clone_insta/Picker.dart:1
#1      _PickState.build
package:clone_insta/Picker.dart:39
#2      StatefulElement.build
package:flutter/…/widgets/framework.dart:4691
#3      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4574

This is where I call and display the image

 return Scaffold(
  body: ListView(
    children: [
      TextButton(
        onPressed: _pickImageCamera,
        child: Text("Pick"),
      ),
      image != (null)
          ? Container(
              color: Colors.grey,
              height: 400,
              width: 100,
              child: Image.file(image),
            )
          : Container(
              color: Colors.grey,
              height: 400,
              width: 100,
              child: Text("No data"),
            )
    ],
  ),
);

enter image description here

Upvotes: 0

Views: 6643

Answers (3)

Vikash Singh
Vikash Singh

Reputation: 51

Just Change

late File image;

to

var image;

Upvotes: 4

KhetheloGP
KhetheloGP

Reputation: 61

What worked for me was to change

from this: File image;

to this: var image;

Upvotes: 1

Jaime Ortiz
Jaime Ortiz

Reputation: 1319

Initialize the your image variable with some image you want your user to see when they open the app, you can use shared_preferences to update the value of the image so when the user reopens the app they see the last image they picked.

If you want to use sharedpreferences, make sure to check is the userImage contains some value and if it does use that path to load the image the user picked last.

class _MyAppState extends State<MyApp> {
  late File image = File('your initial file');
  final picker = ImagePicker();

  void _pickImageCamera() async {
    final pickedImage = await picker.getImage(source: ImageSource.gallery);
    final pickedImageFile = File(pickedImage!.path);
    setState(() {
      image = pickedImageFile;
    });
    prefs.setString('stringValue', "the path to the new image");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: MyApp._title,
      home: Scaffold(
        appBar: AppBar(title: const Text(MyApp._title)),
        body: ListView(
          children: [
            TextButton(
              onPressed: _pickImageCamera,
              child: Text("Pick"),
            ),
            image != (null)
                ? Container(
                    color: Colors.grey,
                    height: 400,
                    width: 100,
                    child: Image.file(image),
                  )
                : Container(
                    color: Colors.grey,
                    height: 400,
                    width: 100,
                    child: Text("No data"),
                  )
          ],
        ),
      ),
    );
  }
}

Upvotes: 3

Related Questions