因此,当用户导航到我的应用程序上的新部分时,我很难保存用户的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();
我尝试了不同的解决方案,但遇到了相同的错误。
1条答案
按热度按时间ipakzgxi1#
在我的情况下,我使用提供者策略保存挑选的照片,并消费他们,每当我想在任何代码,我是,这是我如何进行:
首先,从图像拾取器获取照片:
保存所选照片的提供商:
之后,您可以在任何位置使用添加的照片:
另外不要忘记在顶层父小部件中提供你的Provider类,下面的小例子: