Home > Net >  Image Picker from gallery or camera is not opening when clicking the bottomSheet icons - flutter
Image Picker from gallery or camera is not opening when clicking the bottomSheet icons - flutter

Time:07-16

I am building a registration screen and it is asking the user to choose a profile picture which is implemented inside the CircleAvatar widget, when the user clicks the avatar a bottomSheet appears with Camera Icon and Gallery icon to provide options for the user to select the image, now when i click on the camera icon or the image icon the picker is not showing, here is the CircleAvatar implementation inside a custom widget i build called imageProfile() :

File? image;
  //Creating a new custom widget called imageProfile.
  Widget imageProfile() {
    //stack is a widget used as a wrapper, this wrapper places the elements on top of each other like the stack of books.
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          color: Colors.purple,
          width: 4.0,
        ),
      ),
      child: Center(
        child: Stack(
          // ignore: prefer_const_literals_to_create_immutables
          children: <Widget>[
            // ignore: prefer_const_constructors
            CircleAvatar(
              radius: 80.0,
              backgroundImage: AssetImage("assets/DefaultImage.png"),
            ),
            Positioned(
              bottom: 20,
              right: 20,
              child: InkWell(
                  onTap: () {
                    showModalBottomSheet(
                        context: context,
                        builder: ((builder) => bottomSheet()));
                  },
                  child: Icon(
                    Icons.camera_alt,
                    size: 28,
                  )),
            ),
          ],
        ),
      ),
    );
  }

When the user clicks the Avatar icon a custom bottomSheet widget appears normally which implemented as follows:

//Designing the bottom sheet that appears when clicking the profile image icon to choose from either gallery or take a photo
  Widget bottomSheet() {
    return Container(
      height: 200,
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Column(
        children: <Widget>[
          Text(
            'Choose Profile Picture',
            style: TextStyle(fontSize: 20.0),
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Column(
                children: [
                  IconButton(
                    iconSize: 70,
                    icon: const Icon(Icons.camera),
                    onPressed: () {
                      Future pickImage() async {
                        final image = await ImagePicker()
                            .pickImage(source: ImageSource.camera);
                        if (image == null) return;

                        final imageTemporary = File(image.path);
                        setState(() => this.image = imageTemporary);
                      }
                    },
                  ),
                  Text('Camera')
                ],
              ),
              SizedBox(
                width: 50,
              ),
              Column(
                children: [
                  IconButton(
                    iconSize: 70,
                    icon: const Icon(Icons.image),
                    onPressed: () {
                      pickImage() async {
                        final image = await ImagePicker()
                            .pickImage(source: ImageSource.gallery);
                        if (image == null) return;

                        final imageTemporary = File(image.path);
                        setState(() => this.image = imageTemporary);
                      }
                    },
                  ),
                  Text('Gallery'),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

in the Scaffold the elements or widgets are rendered as follows:

return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        //Use the SingleChildScrollView as a wrapper to ensure scrolling in case scorrling is needed.
        child: SingleChildScrollView(
          //wrap the elements with Container to provide flexibility in designing the elements.
          child: Container(
            color: Colors.white,
            //use the form as a container of the input fields as it is a login form.
            child: Padding(
              padding: const EdgeInsets.all(36.0),
              child: Form(
                //give the form wrapper the key value to tell flutter that this is the form design for your form functions.
                key: _formKey,
                //use the column to show the elements in vertical array.
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    //Use children property inside the column to specify list of widgets
                    children: <Widget>[
                      imageProfile(),
                      SizedBox(
                        height: 20,
                      ),
                    ]),
              ),
            ),
          ),
        ),
      ),
    );
  }

and i haven't forgot the packages added in the pubspec.yaml file and imported in the registration screen:

import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:flutter/material.dart';

i am not sure why its not opening and what i am missing as its not showing any errors, i would be thankful for any help

CodePudding user response:

I used your part of your code and add the pick image function. Each button will trigger different functions and show correctly.

Could you try my code or extract code inside onPressed() as a new function again?

import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';


class photoPicker extends StatefulWidget {
  static const String id = 'photoPicker_screen';

  const photoPicker({Key? key}) : super(key: key);

  @override
  State<photoPicker> createState() => _photoPickerState();
}

class _photoPickerState extends State<photoPicker> {
  File? image;


  void selectImages() async {
    List<XFile>? imageFileList = [];
    final ImagePicker imagePicker = ImagePicker();
    final List<XFile>? selectedImages = await imagePicker.pickMultiImage();
    if (selectedImages!.isNotEmpty) {
      imageFileList!.addAll(selectedImages);
    }
    setState(() {
    });
  }

  void selectImage() async {
    final ImagePicker imagePicker = ImagePicker();
    final XFile? selectedImages = await imagePicker.pickImage(source: ImageSource.gallery);
    setState(() {}
    );
  }

  void selectImagesCamera() async {
    final ImagePicker imagePicker = ImagePicker();
    final XFile? selectedImages = await imagePicker.pickImage(source: ImageSource.camera);
    setState(() {}
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
              'Choose Profile Picture',
              style: TextStyle(fontSize: 20.0),
            ),
            SizedBox(
              height: 20,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Column(
                  children: [
                    IconButton(
                      iconSize: 70,
                      icon: const Icon(Icons.camera),
                      onPressed: () {
                        selectImagesCamera();
                      },
                    ),
                    Text('Camera')
                  ],
                ),
                SizedBox(
                  width: 50,
                ),
                Column(
                  children: [
                    IconButton(
                      iconSize: 70,
                      icon: const Icon(Icons.image),
                      onPressed: () {
                        selectImage();
                      },
                    ),
                    Text('Gallery'),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}


Fig1. Main Screen Fig1. Main Screen Fig2. Camera Mode Fig2. Camera Mode Fig3. Gallery Mode Fig3. Gallery Mode

CodePudding user response:

Because you defined the function but not get it called, try replace open camera code with:

                      Future pickImage() async {
                        final image = await ImagePicker()
                            .pickImage(source: ImageSource.camera);
                        if (image == null) return;

                        final imageTemporary = File(image.path);
                        setState(() => this.image = imageTemporary);
                      }

                      pickImage();

the open gallery code is with the same problem.

  • Related