Access Camera and Gallery in Flutter

Flutter provides an image picker library to add images directly from the gallery. Hence, all the applications fetch images from a camera or gallery. 

The following are the steps to set images in an Android application.

Step 1: Create a new project or use already existing Flutter projects. 



Step 2: Add dependency to your pubspec.yaml file.

   dev_dependencies:

      Flutter_test:

      sdk: flutter

      image_picker: ^1.1.1


Step 3: Create a main.dart and write the camera and gallery code.  

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

import 'package:image_picker/image_picker.dart';

 

void main() {

runApp(MyApp());

}

 

//create class of myapp

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: MyHomePage(),);}}

 

class MyHomePage extends StatefulWidget {

@override

_MyHomePageState createState() => _MyHomePageState();}

 

class _MyHomePageState extends State<MyHomePage> {

late File _image;

//create object of ImagePicker

final picker = ImagePicker();

 

//Image Picker function to get image from gallery

Future getImageFromGallery() async {

final pickedFile = await picker.getImage(source: ImageSource.gallery);

 

//change state 

setState(() {

if (pickedFile != null) {

_image = File(pickedFile.path);

}

});

}

 

//Image Picker function to get image from camera

Future getImageFromCamera() async {

final pickedFile = await picker.getImage(source: ImageSource.camera);

 

//change state 

setState(() {

if (pickedFile != null) {

_image = File(pickedFile.path);

}

});

}

 

//Show options to get image from camera or gallery

Future showOptions() async {

showCupertinoModalPopup(

context: context,

builder: (context) => CupertinoActionSheet(

actions: [

CupertinoActionSheetAction(

child: Text('Photo Gallery'),

onPressed: () {

// close the options modal

Navigator.of(context).pop();

// get image from gallery

getImageFromGallery();

},

),

CupertinoActionSheetAction(

child: Text('Camera'),

onPressed: () {

// close the options modal

Navigator.of(context).pop();

// get image from camera

getImageFromCamera();},),],),);}

 

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Image Picker Example'),

),

body: Column(

children: [

TextButton(

child: Text('Select Image'),

onPressed: showOptions,

),

Center(

child: _image == null ? Text('No Image selected') : Image.file(_image),),],),);}}

 

Step 4: Output of above code.


Happy coding!














365Bloggy May 14, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive