anangfaturrohman
anangfaturrohman

Reputation: 441

How to use image_picker in flutter

I am confused about how to use image_picker, this is how I use it in my application (like in many tutorials):

class AddDialogState extends State<AddDialog> {
    File galleryFile;
    Widget _onlyStatus() {
         getLocalImage() async {
               var _galleryFile = await ImagePicker.pickImage(
                     source: ImageSource.gallery
               };
               setState(() {
                   galleryFile = _galleryFile;
               });
               print(_galleryFile.path);
         }

         return Column(
               ........
               FlatButton.icon(
                    onPressed: () {
                         getLocalImage();
                    }
               )
         )

    }

    @override
    Widget build(BuildContext context) {
         // fullscreen dialog
         .........
         body: _onlyStatus()
    }
}

The problem was, the above code doesn't start ImagePicker, when i click the FlatButton, the above code just produce an error the getter 'path' was called on null, it doesn't start any new activity related to gallery, so what's wrong with my code?

Upvotes: 3

Views: 7039

Answers (4)

Miguel Rosal
Miguel Rosal

Reputation: 189

Here is my code for image_picker: ^0.8.4+4 (flutter 2.8.1)

bool hasImage = false;
File? image;

Future getImage(ImageSource source) async {
    try {
      final image = await ImagePicker().pickImage(source: source);
      if (image == null) return;
      final imageTemporary = File(image.path);
      setState(() {
        this.image = imageTemporary;
        hasImage = true;
      });
    } on PlatformException catch (e) {
      debugPrint('Failed to pick image: $e');
    }
  }

Upvotes: 0

beginner
beginner

Reputation: 213

flutter imagepicker- pickimage deprecated.

Actually pickImage() is deprecated now. So you have to use ImagePicker.getImage(source: ImageSource.gallery)

Click here for more

void getImage(ImageSource imageSource) async {
    PickedFile imageFile = await picker.getImage(source: imageSource);
    if (imageFile == null) return;
    File tmpFile = File(imageFile.path);
    final appDir = await getApplicationDocumentsDirectory();
    final fileName = basename(imageFile.path);
    tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
    setState(() {
      _image = tmpFile;
    
    });
  }

The code also store image file in device directory. Path pacakage is also used.

Upvotes: 3

Hairon Chaviano
Hairon Chaviano

Reputation: 443

your showDialog should be something like this:

Container(
          width: 300,
          height: 300,
          child: GestureDetector(
            onTap: () {
              showDialog(
                context: context,
                builder: (BuildContext context) => showSelector(
                      context,
                      "Select",
                      actions: [
                        SelectionItem(
                          "Camera",
                          action: () {
                            getImage(ImageSource.camera);
                            Navigator.of(context).pop();
                          },
                        ),
                        SelectionItem(
                          "Gallery",
                          action: () {
                            getImage(ImageSource.gallery);
                            Navigator.of(context).pop();
                          },
                        )
                      ],
                    ),
              );
            },
          ),
        )

Upvotes: 0

Hairon Chaviano
Hairon Chaviano

Reputation: 443

Here is my example you only need to call the SelectionItem and pass the required parameters and it's done, also it includes support for Android and iOS.

class SelectionItem {
  String text;
  GestureTapCallback action;

  SelectionItem({
    this.text,
    this.action,
  });
}

Widget _getOptionWidget(SelectionItem item) {
  return SimpleDialogOption(
    onPressed: item.action,
    child: Text(item.text),
  );
}

Widget _getCupertinoOptionWidget(SelectionItem item) {
  return CupertinoActionSheetAction(
    onPressed: item.action,
    child: Text(item.text),
  );
}

showSelector(
  BuildContext context, {
  String title,
  List<SelectionItem> actions,
}) {
  bool isAndroid = Injector.instance.platform == Platform.ANDROID;

  if (isAndroid) {
    final items = actions.map((action) => _getOptionWidget(action)).toList();
    return SimpleDialog(
      title: Text(title),
      children: items,
    );
  } else {
    final items =
        actions.map((action) => _getCupertinoOptionWidget(action)).toList();

    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        CupertinoActionSheet(
          title: Text(title),
          actions: items,
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              NavigationUtils.pop(context);
            },
            child: Text("Cancel"),
          ),
        ),
      ],
    );
  }
}

Upvotes: 0

Related Questions