如何在Flutter中从相册或相机选择图像

huangapple go评论55阅读模式
英文:

How to pick image from gallery or camera in flutter

问题

我是新手学习Flutter,我想根据用户的选择从相册或相机中选择并显示一张图片。相册已经打开,但当我选择一张图片时,它没有显示出来,但如果我将拍照的代码从控制器类移到有状态的类中,一切都能正常工作,因为有状态的类中可以使用setState函数,而不是控制器中使用的update()函数。我认为问题在于控制器类中的update函数不起作用。

class CustomerController extends GetxController {

  PickedFile? _imageFile;
  PickedFile? get pickedFile => _imageFile;
  final _imagePicker = ImagePicker();

  // 用于从相册或相机中选择图片
  Future<void> takePhoto(ImageSource source) async {
    _imageFile = await _imagePicker.getImage(source: source);
    update();
  }
}

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

  @override
  _SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {

  var imageController = Get.find<CustomerController>();

  // 在这里使用选定的图片
  Positioned(
    top: Dimension.height40 + Dimension.height30,
    left: MediaQuery.of(context).size.width / 2 - 75,
    child: Container(
      child: CircleAvatar(
        radius: 70,
        backgroundImage: imageController.pickedFile == null
            ? AssetImage("assets/images/profile.png")
            : FileImage(File(imageController.pickedFile!.path)) as ImageProvider,
      ),
    ),
  ),
  // 其他部分...
}

这是您提供的代码的翻译部分。如有疑问,请随时提出。

英文:

I am new to flutter and I want to pick and display an image from either gallery or camera depending on user's choice.
The gallery opened but when I pick an image, it's not been displayed but if I move the code for taking the photo from the controller class to the stateful class, the thing works well because with stateful class, I can use setState function rather than the update() used in the controller. I think the issue is that the update function in the controller class is not working

class CustomerController extends GetxController{

PickedFile? _imageFile;
  PickedFile? get pickedFile =&gt; _imageFile;
  final  _imagePicker = ImagePicker();

//for picking an image from either gallery or Camera
  Future&lt;void&gt; takePhoto(ImageSource source)async{
    _imageFile = await _imagePicker.getImage(
        source: source);
    update();
  }
}

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

  @override
  _SignUpScreenState createState() =&gt; _SignUpScreenState();
}

class _SignUpScreenState extends State&lt;SignUpScreen&gt; {

var imageController = Get.find&lt;CustomerController&gt;();

Positioned(
            top: Dimension.height40+Dimension.height30,
            left: MediaQuery.of(context).size.width /2-75,
            child: Container(
              child: CircleAvatar(
                radius: 70,
                backgroundImage: imageController.pickedFile==null? AssetImage(&quot;assets/images/profile.png&quot;):
                FileImage(File(imageController.pickedFile!.path)) as ImageProvider
              ),
            )
          ),
        ],
      ),
    );
  }
  Widget _bottomSheetProfile(){
    return Container(
      height: Dimension.height20*8,
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.symmetric(horizontal: 20,vertical: 20),
      child: Column(
        children: [
          Text(
            &quot;Choose A Profile Photo&quot;,
            style: TextStyle(
              fontSize: 20,
              color: Color(0xff8F6ED5)
            ),
          ),
          SizedBox(
            height: Dimension.height20/2,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              IconButton(
              onPressed: (){
                imageController.takePhoto(ImageSource.camera);
              },
              icon: Icon(Icons.camera_alt_rounded,
                color: Color(0xff8F6ED5),
              size: 30,)),
              IconButton(
                  onPressed: (){
                    imageController.takePhoto(ImageSource.gallery);
                  },
                  icon: Icon(Icons.image,
                    color: Color(0xff8F6ED5),
                    size: 30,))
            ],
          ),
          SizedBox(height: Dimension.height20/5,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: const [
              Text(
                &quot;Camera&quot;,
                style: TextStyle(
                  fontSize: 18,
                  color:Color(0xff8F6ED5)
                ),
              ),
              Text(
                &quot;Gallery&quot;,
                style: TextStyle(
                    fontSize: 18,
                    color:Color(0xff8F6ED5)
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  _showButtonSheet(){
    showModalBottomSheet(
        context: context,
        builder: ((builder)=&gt; _bottomSheetProfile()));
  }

答案1

得分: 2

将容器包装在GetBuilder中,就像下面的示例一样:

GetBuilder<ImageController>(
  builder: (_) {
    return controller.image != null
      ? Image.file(controller.image)
      : Container();
  },
),
英文:

Wrap the container with GetBuilder like below example:

GetBuilder&lt;ImageController&gt;(
  builder: (_) {
    return controller.image != null
      ? Image.file(controller.image)
      : Container();
  },
),

答案2

得分: 0

你也可以使用Obx来观察文件:

Obx(
    () => imageController.image != null
        ? Image.file(imageController.image)
        : Container()
);
英文:

You can also use Obx to observe the file :-

              Obx(
                  () =&gt; imageController.image != null
                        ? Image.file(imageController.image)
                        : Container();
                )

huangapple
  • 本文由 发表于 2023年6月19日 17:19:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505251.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定