Home > OS >  Flutter, how to get gallery image and set as Avatar?
Flutter, how to get gallery image and set as Avatar?

Time:12-23

I am still new to Flutter, can someone tell how to select an image as Avatar? Also, I would like to show the same image when user comes back to the app next time, should I only store the path in local file will do?

part of my code:

XFile? headImage;

child: ListView(
        padding: EdgeInsets.zero,
        children: [
          GestureDetector(
            onTap: () {
              selectImage();
            },
            child: UserAccountsDrawerHeader(
              decoration: BoxDecoration(color: Colors.teal),
              accountName: Text(
                globals.userName,
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              accountEmail: Text(
                '',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              currentAccountPicture: CircleAvatar(
                backgroundColor: Colors.brown,
//                backgroundImage: AssetImage('images/cookie.JPG'),
                backgroundImage: Image.file(File(headImage.path)).image,
              ),
            ),
          ),
Future<void> selectImage() async {
  ImagePicker _picker = ImagePicker();
  XFile? image = await _picker.pickImage(source: ImageSource.gallery);
  headImage = image;
  print(headImage?.path);
}

I can get headImage?.path, but I can't assign back to the Avatar but get error: Property 'path' cannot be accessed on 'XFile?' because it is potentially null.

CodePudding user response:

add variable for image:

File? _avatarFile;

set data for _avatarFile after image picked:

Future<void> selectImage() async {
  ImagePicker _picker = ImagePicker();
  XFile? image = await _picker.pickImage(source: ImageSource.gallery);
 
  setState((){
    _avatarFile = File(image.path ?? '');
  });
}

Now you can use _avatarFile for FileImage();

currentAccountPicture: _avatarFile != null
          ? CircleAvatar(
              backgroundColor: Colors.brown,
              backgroundImage: FileImage(_avatarFile!),
            )
          : const CircleAvatar(
              backgroundColor: Colors.brown,
              backgroundImage: AssetImage('images/cookie.JPG'),
            ),
  • Related