skip to Main Content

i want to create a function in flutter to pick image from gallery and camera in my page. can someone help me with this code please.

enter image description here

enter image description here

import 'package:flutter/material.dart';

class Productdetails extends StatefulWidget {
  const Productdetails({super.key});

  @override
  State<Productdetails> createState() => _ProductdetailsState();
}

class _ProductdetailsState extends State<Productdetails> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.orange,
        title: const Text('Product List'),
        titleTextStyle: const TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 22,
            wordSpacing: 2.5,
            color: Colors.black),
        centerTitle: true,
        actions: [
          IconButton(onPressed: () {}, icon: const Icon(Icons.save)),
        ],
      ),
      body: const Padding(padding: EdgeInsets.symmetric(vertical: 20,horizontal: 20),
      child: Text(
'Product Image',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),
      ),
      ),
    );
  }
}

2

Answers


  1. You can you either the image_picker or file_picker package.

    The image_picker has a future function that allows you to pick image from gallery or camera and it returns a file object. You can use the path to that file to set your image.

    The file_picker allows you to pick any file from your storage either image, video etc. But you can put restrictions on it to select only images.

    Login or Signup to reply.
  2. This is part of your State class in a Stateful widget:

    import 'dart:io';
    import 'package:image_picker/image_picker.dart';
    
        class _SnapshotState extends State<Snapshot> {
          File? _imgFile;
        
          void takeSnapshot() async {
            final ImagePicker picker = ImagePicker();
            final XFile? img = await picker.pickImage(
              source: ImageSource.camera, // alternatively, use ImageSource.gallery
              maxWidth: 400,
            );
            if (img == null) return;
            setState(() {
              _imgFile = File(img.path); // convert it to a Dart:io file
            });
          }
        }
    

    Code snippet to display the image in an Avatar:

    CircleAvatar(
      radius: 32,
      backgroundImage: (_imgFile == null)
      ? AssetImage('assets/person.png')
      : FileImage(_imgFile!) as ImageProvider,
    )
    

    In case image loading/clicking fails, you should have a dafault image in your project assets. Include it in your pubspec.yaml file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search