image_picker flutter错误,如何在应用程序中永久保存图像?

k2arahey  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(137)

因此,当用户导航到我的应用程序上的新部分时,我很难保存用户的pfp,当用户从当前选项卡单击并返回时,pfp消失了,它杀死了它似乎的路径。我希望能够上传一个图像作为pfp,当我导航到应用程序内的新部分时,它仍然在那里。代码如下:

import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';

import 'save_pfp.dart';

File? image;
class BuildProfile extends StatefulWidget {
  
  const BuildProfile({super.key});
  @override
  State<BuildProfile> createState() => _BuildProfileState();
}
class _BuildProfileState extends State<BuildProfile> {



 Future getImage() async{
  try{
    image = (await ImagePicker().pickImage(source: ImageSource.gallery)) as File?  ;
    if (image == null) return;
    
 final imagePermanent = await saveImagePermanently(image!.path);
    setState(() => image = imagePermanent);
  } on PlatformException catch (e) {
    print('failed to pick image: $e');
  }
 }

 Future<File> saveImagePermanently(String imagePath) async{
  final directory = await getApplicationDocumentsDirectory();
final fileName = basename(imagePath);
 image = File('${directory.path}/$fileName');
  return File(imagePath).copy(image!.path);
}





  @override
  Widget build(BuildContext context) {
    return CircleAvatar(
                      backgroundColor: Colors.grey.shade400,
                      backgroundImage: image == null ? null
                      : FileImage(image!),
                      radius: 56,
                      child: Align(
                        alignment:const  Alignment(3.2, 0.73),
                        child: RawMaterialButton(
                        onPressed: () {
                         showModalBottomSheet(context: context, 
                         backgroundColor: Colors.black38,
                           builder: (context) =>  Container(
                            height: 180,
                       child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                      const Text('camera',
                    style: TextStyle(color: Colors.white)),
                  IconButton(
                 onPressed: () {
                  // _getFromCamera;
              getImage();
                  },
                icon: const Icon(CupertinoIcons.camera, 
                 size: 26,
                color: Colors.white,
                           )),
                 IconButton(
                 // pick from gallery
                onPressed:() {
                getImage();

我尝试了不同的解决方案,但遇到了相同的错误。

ipakzgxi

ipakzgxi1#

在我的情况下,我使用提供者策略保存挑选的照片,并消费他们,每当我想在任何代码,我是,这是我如何进行:
首先,从图像拾取器获取照片:

void _setImageFromPhone(ImageSource imageSource) async {
    final pickedFile = await ImagePicker().pickImage(source: imageSource, imageQuality: 75);

    if (pickedFile == null) {
      return;
    }

    log(pickedFile.path);
    widget.formModel.addNewPhotos(pickedFile.path);
  }

保存所选照片的提供商:

class FormModel extends ChangeNotifier {
  final List<String> _photos = [];

  void addNewPhotos(String photo) {
    _photos.add(photo);
    notifyListeners();
  }

  //getter for photos
  UnmodifiableListView<String> get photos => UnmodifiableListView(_photos);
}

之后,您可以在任何位置使用添加的照片:

@override
  Widget build(BuildContext context) {
    return Consumer<FormModel>(
      key: formModelConsumerKey,
      builder: (
        context,
        formModel,
        child,
      ) {
        return 
            Row(
                children:[

                ]
            )
        Container(
              height: MediaQuery.of(context).size.width * 0.35,
              width: MediaQuery.of(context).size.width * 0.35,
              decoration: BoxDecoration(
                color: LIGHT_GREEN_COLOR,
                borderRadius: const BorderRadius.all(
                  Radius.circular(10),
                ),
                image: DecorationImage(
                  image: Image.file(File(formModel.photos.first!)).image,
                  fit: BoxFit.fill,
                ),
              ),
              child: SizedBox();
              );

        }
        );
        }

另外不要忘记在顶层父小部件中提供你的Provider类,下面的小例子:

return MultiProvider(
            providers: [
              ChangeNotifierProvider(create: (context) => FormModel()),
            ],
            child: MaterialApp()           
        )

相关问题