首页 > 解决方案 > 照片没有显示 image_picker- Flutter

问题描述

我无法处理image_picker。当我选择一张照片时,我应该看到照片而不是头像图标,但我不知道为什么它不能那样工作。我是颤振的新手,也许应该以不同的方式解决。

橙色圆圈应该保留,图标应该改变,任何建议对我来说都会很好

 Widget _avatar() {
   return const CircleAvatar(
       radius: 83,
  backgroundColor: Colors.orange,
  child: CircleAvatar(
    backgroundColor: Colors.white,
    radius: 80,
    child: Icon(Icons.person_outline, size: 60, color: Colors.orange),
  ),
);
}

File? _image;
final picker = ImagePicker();

Future getImage() async {
  final pickedFile = await picker.getImage(
    source: ImageSource.gallery, maxWidth: 1800, maxHeight: 1800);

setState(() {
  if (pickedFile != null) {
    _image = File(pickedFile.path);
  } else {
    print('No image selected.');
  }
});
}

Future getCameraImage() async {
final pickedFile = await picker.getImage(
  source: ImageSource.camera,
  maxWidth: 1800,
  maxHeight: 1800,
);

setState(() {
  if (pickedFile != null) {
    _image = File(pickedFile.path);
  } else {
    print('No image selected.');
  }
});
}

void _showPicker(BuildContext context) {
showModalBottomSheet<void>(
    context: context,
    builder: (BuildContext bc) {
      return SafeArea(
        child: Container(
          child: Wrap(
            children: <Widget>[
              ListTile(
                  leading: new Icon(Icons.photo_size_select_large_sharp),
                  title: new Text('Photo Library'),
                  onTap: () {
                    getImage();
                    Navigator.of(context).pop();
                  }),
              ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text('Camera'),
                onTap: () {
                  getCameraImage();
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        ),
      );
    });
}

Widget _changeAvatarButton(BuildContext context) {
return Column(
  children: [
  CircleAvatar(
  radius: 83,
  backgroundColor: Colors.orange,
      child: _image == null ? _avatar() : Image.file(_image!),
    ),
    CustomButtonText(
        onPressed: () {
          _showPicker(context);
        },
        title: 'photo',
        textColor: Colors.teal),
  ],
);
  }

在此处输入图像描述

标签: flutterdartflutter-layoutflutter-dependencies

解决方案


用下面的小部件更改您的 CircleAvtar 小部件,如果您不想显示橙色圆圈,请设置 backgroundColor: _image == null ?Colors.orange:颜色.透明。

CircleAvatar(
  radius: 83,
  backgroundColor: Colors.orange,
  child: _image == null
      ? _avatar()
      : ClipRRect(
          borderRadius: BorderRadius.circular(83),
          child: Image.file(
            _image!,
            height: 160, // Change the size up or down accordingly border radius
            width: 160, // Change the size up or down accordingly border radius
            fit: BoxFit.cover,
          )),
),

推荐阅读