Setting image as default using Uint8List and ImagePicker

487 Views Asked by At

I have a profile screen that prompts user to enter information and there's a image picker for the profile image.

I use Uint8List to store the picked image and upload to a database.

How do I make an image in assets the default image if the user doesn't select an image?

class _SignUpScreenState extends State<SignUpScreen> {

  Uint8List? _image;

  @override
  void dispose() {...}

  void selectImage() async {
    Uint8List imageFile = await pickImage(ImageSource.gallery);

    setState(() {
      _image = imageFile;
    });
  }

  void signupUser() async {
    final navigator = Navigator.of(context);
    if (_image == null) {
      //set default image as profile
      showSnackBar('Please select image', context);
      return;
        }
    setState(() {...}

My ImagePicker is as follows:

pickImage(ImageSource source) async {
  final ImagePicker _imagePicker = ImagePicker();

  XFile? _file = await _imagePicker.pickImage(source: source);

  if (_file != null) {
    return await _file.readAsBytes();
  }
}

showSnackBar(String content, BuildContext context) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(content),
    ),
  );
}

The default image is an SVG as well but I have a png too.

1

There are 1 best solutions below

0
Bharath On

Simply check the null state of Unit8List variable

/// for png assets
_image == null ? Image.asset("<asset file path>") : Image.memory(_image!)

For svg image use flutter_svg package

_image == null ? SvgPicture.asset("<asset file path>") : Image.memory(_image!)