How to make image fit in circular avatar in flutter?

Viewed 122

I'm using a circle avatar on the sign-up page to let users can upload their profile images. However, the size of the image doesn't fit in the circle avatar. The image is too big for the circle avatar and I want to make it fit. How can I fix this problem? Thank you

The original profile image enter image description here

How it looks in circle avatar enter image description here

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

class SignupProfileImage extends StatefulWidget {
  SignupProfileImage({Key? key}) : super(key: key);

  @override
  State<SignupProfileImage> createState() => _SignupProfileImageState();
}

class _SignupProfileImageState extends State<SignupProfileImage> {
  bool isUploadImage = false;
  var selectedImage;

  uploadProfileImage () async{
    var picker = ImagePicker();
    var image = await picker.pickImage(source: ImageSource.gallery);
    if(image != null) {
      setState(() {
        selectedImage = image.path;
      });
    }
    if (!mounted) return;
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
        top: 140,
        right: 0,
        left: 0,
        child: SizedBox(
          height: 100,
          width: 100,
          child: Stack(
            clipBehavior: Clip.none,
            fit: StackFit.expand,
            children: [
              CircleAvatar(
                backgroundImage: isUploadImage && selectedImage != null ? FileImage(File(selectedImage)) : AssetImage('assets/face.jpg') as ImageProvider,
              ),
              Positioned(
                  bottom: -5,
                  left: 0,
                  right: -50,
                  child: RawMaterialButton(
                    onPressed: () {
                      uploadProfileImage();
                      setState(() {
                        isUploadImage = true;
                      });
                    },
                    elevation: 2.0,
                    fillColor: const Color(0xFFF5F6F9),
                    padding: const EdgeInsets.all(5.0),
                    shape: const CircleBorder(),
                    child: const Icon(Icons.camera_alt_outlined, color: Colors.blue,),
                  )
              ),
            ],
          ),
        )
    );
  }
}

1 Answers

You can use ClipRRect widget, wrap you Image widget with ClipRRect and pass borderRadius, you will get what you want. and you can fit Image by passing BoxFit.fitheight to Image widget:

Example:

ClipRRect(
       borderRadius: BorderRadius.circular(100),
       child: Image.asset(
                 'assets/images/tutorial_1_bg.png',
                  height: 200.0,
                  width: 200.0,
                  fit: BoxFit.fill,
                ),
              )
Related