当我尝试删除数据库中的文件(之前已删除)时,它显示以下内容:“没有为类型”Reference“定义方法”exists“。“
我认为这是因为当我发送调用路径时,它没有找到任何文件,这就是为什么它提到我它不存在。
没有为类型“Reference”定义方法“exists”。
请尝试将名称更正为现有方法的名称,或定义名为“exists”的方法
String ref = _selectedRef!;
if (!ref.startsWith("/")) {
ref = "/" + ref;
}
ref = ref.substring(0, ref.lastIndexOf("/") + 1) + ".pdf";
我的问题是:
// validate if the reference exists
**bool exists = await FirebaseStorage.instance.ref(ref).exists();**
这里我们需要等待是否存在引用:
if (exists) {
await FirebaseStorage.instance.ref(ref).delete();
await FirebaseFirestore.instance
.collection("file")
.where("ref", isEqualTo: _selectedRef)
.get()
.then((snapshot) {
snapshot.docs.first.reference.delete();
});
setState(() {
_selectedRef = null;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("El archivo seleccionado no existe")));
}
}
这是我的完整代码:
import 'dart:io';
import 'dart:math';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:file_picker/file_picker.dart';
import 'package:fimprac/screen_acercade.dart';
import 'package:fimprac/screen_home.dart';
import 'package:fimprac/main.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/material/navigation_drawer.dart';
import 'package:fimprac/menu.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: perfilSC(),
));
}
class perfilSC extends StatefulWidget {
const perfilSC({super.key});
@override
State<perfilSC> createState() => _perfilSCState();
}
class _perfilSCState extends State<perfilSC> {
String?
_selectedRef; //agrega una variable para almacenar la referencia del archivo seleccionado
String url = "";
int? number;
late QueryDocumentSnapshot selectedSnapshot;
uploadDataToFirebase() async {
//generate random number
number = Random().nextInt(10);
//pick pdf file
FilePickerResult? result = await FilePicker.platform.pickFiles();
File pick = File(result!.files.single.path.toString());
var file = pick.readAsBytesSync();
String name = DateTime.now().millisecondsSinceEpoch.toString();
//uploading file to firebase
var pdfFile = FirebaseStorage.instance.ref().child(name).child("/.pdf");
UploadTask task = pdfFile.putData(file);
TaskSnapshot snapshot = await task;
url = await snapshot.ref.getDownloadURL();
String ref = name + "/.pdf"; // establece la referencia del archivo
//upload to url to cloud firebase
await FirebaseFirestore.instance.collection("file").doc().set({
'fileUrl': url,
'num': "CV#" + number.toString(),
'ref': name + "/.pdf" // agrega la referencia del archivo
});
}
Future<void> deleteFile() async {
if (_selectedRef != null) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('¿Estás seguro que quieres eliminar el archivo?'),
actions: <Widget>[
TextButton(
child: Text('Cancelar'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('Eliminar'),
onPressed: () async {
await deleteFirebaseData();
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Archivo eliminado")));
},
),
],
);
},
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Selecciona un archivo para eliminar")));
}
}
Future<void> deleteFirebaseData() async {
if (_selectedRef == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Selecciona un archivo para eliminar")));
return;
}
// construir la ruta completa de la referencia del archivo
String ref = _selectedRef!;
if (!ref.startsWith("/")) {
ref = "/" + ref;
}
ref = ref.substring(0, ref.lastIndexOf("/") + 1) + ".pdf";
// validar si la referencia existe
bool exists = await FirebaseStorage.instance.ref(ref).exists();
if (exists) {
await FirebaseStorage.instance.ref(ref).delete();
await FirebaseFirestore.instance
.collection("file")
.where("ref", isEqualTo: _selectedRef)
.get()
.then((snapshot) {
snapshot.docs.first.reference.delete();
});
setState(() {
_selectedRef = null;
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("El archivo seleccionado no existe")));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const NavigationDrawerMenu(),
appBar: AppBar(
backgroundColor: Colors.green,
title: Text('PDF'),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection("file").snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, i) {
QueryDocumentSnapshot x = snapshot.data!.docs[i];
return InkWell(
onTap: () {
setState(() {
selectedSnapshot = x; // asignar valor a la variable
});
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => View(
url: x['fileUrl'],
)));
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Text(x["num"]),
),
);
});
}
return Center(
child: CircularProgressIndicator(),
);
}),
floatingActionButton: Row(
children: [
FloatingActionButton(
heroTag: "btn1",
onPressed: () {
setState(() {
_selectedRef = selectedSnapshot[
'ref']; //almacena la referencia del archivo seleccionado
});
deleteFile();
},
child: Icon(Icons.delete),
),
SizedBox(width: 10),
Expanded(
child: FloatingActionButton(
heroTag: "btn2",
onPressed: () => uploadDataToFirebase(),
child: Icon(Icons.add),
),
),
],
),
);
}
}
class View extends StatelessWidget {
PdfViewerController? _pdfViewerController;
final url;
View({this.url});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("PDF VIEW"),
),
body: SfPdfViewer.network(
url,
controller: _pdfViewerController,
),
);
}
}
1条答案
按热度按时间hfyxw5xn1#
正如消息所说,云存储没有
.exists
方法。那是一种用来检查设备本地存储上文件的方法。按照此文档检查云存储上存在的文件... https://jsmobiledev.com/article/storage-file-exist/这是针对JavaScript的,但原理是相同的。