Home > Enterprise >  imagepicker flutter cant be used
imagepicker flutter cant be used

Time:09-29

im new in flutter and i made a project using this, i have a problem that
when i want to use imagepicker it couldn't be used i have following step by step on youtube and i getting error on

"File imageFile; says non-nullable instance field ' imageFile' must be initialized."

and on "Pickedfile.path says the propety 'path' can't be unconditionally accessed because the receiver can be 'null'."

this is my writed code

  File imageFile;
  final picker = ImagePicker();

  chooseImage(ImageSource source) async {
    final PickedFile = await picker.pickImage(source: source);

    setState(() {
      imageFile = File(PickedFile.path);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {},
          icon: Icon(Icons.exit_to_app),
        ),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                  child: imageFile != null
                      ? Container(
                          height: 120.0,
                          width: 120.0,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                            image: FileImage(imageFile),
                          )),
                        )
                      : Container(
                          height: 120.0,
                          width: 120.0,
                          decoration: BoxDecoration(color: Colors.blue),
                        )),
              Container(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: ElevatedButton(
                    onPressed: () {
                      chooseImage(ImageSource.gallery)
                    },
                    child: Text('Ubah Foto Profil'),
                  ),
                ),
              ),

CodePudding user response:

This is because you are initializing file path with null give some value and than change it using setstate()

CodePudding user response:

Let me know if it works for you.

 ImagePicker picker = ImagePicker();
 File imageFile;

  Future chooseImage(ImageSource source) async {
    var pickedFile = (await picker.pickImage(source: source));
    File selected = File(pickedFile.path);

    imageFile = selected;

  }
  • Related