flutter

how to upload image from gallery with flutter

In this article we will see briefly how to upload an image from a gallery in a easy, fast and simple way.

First we have to use Image Picker, a package that will make our life easy, let's add the package to our pubspec.yaml file under the dependecies.

Dart
dependencies:
  image_picker: ^0.6.7+7

Now let's go into the dart file where we want to use it and import it as follows and import the dart:io package to that we will need later when calling the File widget

Dart
import 'dart:io';
import 'package:image_picker/image_picker.dart';

Good now we are ready to create a simple function where we will call the image picker.

Dart
void _uploadImage() async {

    final _picker = ImagePicker(); 

    var _pickedImage = await _picker.getImage(source: ImageSource.gallery);

    setState(() {
      image = _pickedImage.path;      
    });
    
}

When calling ImagePicker it will save an instance inside our _picker variable that then we will use to access the getImage method passing as source the gallery, that means that we want the gallery as source method.

After doing so we update the state of the image variable created inside the home page state so we can use it inside our File widget.

dart
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var image;

  void _uploadImage() async {

    final _picker = ImagePicker();

    var _pickedImage = await _picker.getImage(source: ImageSource.gallery);

    setState(() {
      image = _pickedImage.path;      
    });
    
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        // Using the file widget to show our image
        child: image != null ? Image.file(File(image)) : null
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _uploadImage,
        tooltip: 'Upload image',
        child: Icon(Icons.image),
      ),
    );
  }
}

This is the entire class Stateless app used for this example. 

With this i hope that you learned how to upload an image from your phone, for more follow our Youtube page.

flutter upload image upload flutter image picker gallery flutter upload gallery flutter
Expand your knowledge about this topic