如何在flutter中从另一个小部件刷新列表视图?

wpx232ag  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(163)

我是flutter的新手,在我的PDF应用程序中添加一个文件后,我试图刷新我的文件列表。我使用的列表视图和添加按钮在不同的部件中。我使用的刷新功能是为删除按钮工作的,它与列表视图在同一个部件中,而为添加按钮提供错误,它与列表视图在不同的部件中。在这两种情况下,我都试图更新列表视图。
`

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

  @override
  State<ListFiles> createState() => _ListFilesState();
}

class _ListFilesState extends State<ListFiles> {
  final storage = FirebaseStorage.instance;
  late Future<ListResult> futureFiles;

  String pathPDF = "";

  final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    futureFiles = FirebaseStorage.instance.ref('files').listAll();
  }

  @override
  Widget build(BuildContext context) => SizedBox(
        height: 450,
        child: RefreshIndicator(
          onRefresh: onRefresh,
          child: FutureBuilder<ListResult>(
            future: futureFiles,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final files = snapshot.data!.items;

                return  ListView.builder(
                    itemCount: files.length,
                    itemBuilder: (context, index) {
                      final file = files[index];

                      return ListTile(
                        title: Text(file.name),
                        onTap: ()  async {
                          String url = await getFirebaseDownUrl(file);
                          Navigator.push(context,
                              MaterialPageRoute(builder: (BuildContext context) =>
                                  Scaffold(
                                      appBar: AppBar(
                                          title: Text(file.name),
                                        backgroundColor: Colors.red,
                                      ),
                                      body: SfPdfViewer.network(
                                        url,
                                        key: _pdfViewerKey,
                                      )
                                  ),
                              ),
                          );
                        },
                        trailing: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            IconButton(
                              onPressed: () {
                                _dialogBuilder(context, file);
                              },
                              icon: const Icon(
                                Icons.delete,
                                color: Colors.red,
                              ),
                            ),
                          ],
                        ),
                      );
                    }
                );
              } else if (snapshot.hasError) {
                return Column(
                  children: [
                    ListTile(
                      leading: const Icon(
                        Icons.error,
                        color: Colors.redAccent,
                      ),
                      title: const Text('Error occurred'),
                      trailing: IconButton(
                        onPressed: () {
                          setState(() {
                            onRefresh();
                          });
                        },
                        icon: const Icon(
                          Icons.refresh,
                          color: Colors.blue,
                        ),
                      ),
                    ),
                  ],
                );
              } else {
                return const Center(
                  child: CircularProgressIndicator(),
                );
              }
            },
          ),
        ),
      );

  Future<String> getFirebaseDownUrl(Reference ref) async {
    print(await ref.getDownloadURL());
    return ref.getDownloadURL();
  }

  Future downloadFile(Reference ref) async {
    List<int> textBytes = utf8.encode('{$ref}');
    Uint8List data = Uint8List.fromList(textBytes);
    String mimeType = "application/pdf";

    DocumentFileSavePlus.saveFile(data, ref.name, mimeType);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Downloaded ${ref.name} successfully')),
    );
  }

  Future deleteFile(Reference ref) async {
    // Create a reference to the file to delete
    final storageRef = FirebaseStorage.instance.ref();
    final deleteRef = storageRef.child(ref.fullPath);

    // Delete the file
    await deleteRef.delete();

    // setState(() {
    //   futureFiles = FirebaseStorage.instance.ref('files').listAll();
    // });
    // build(context);

    onRefresh();

    //  WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));

    ScaffoldMessenger.of(context).showSnackBar(
      // SnackBar(content: Text('Deleted file ${ref.name}')),
      SnackBar(
        content: Row(
          children: [
            Text('${ref.name} deleted successfully'),
            const Spacer(
              flex: 2,
            ),
            TextButton(
              onPressed: () {
                onRefresh();
              },
              child: const Text(
                'Refresh',
                style: TextStyle(color: Colors.blue),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _dialogBuilder(BuildContext context, Reference file) {
    return showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Warning'),
          content: const Text('Are you sure you want to delete the file?'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('NO', style: TextStyle(color: Colors.green)),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                deleteFile(file);
              },
              child:
                  const Text('YES', style: TextStyle(color: Colors.redAccent)),
            ),
          ],
        );
      },
    );
  }

  Future onRefresh() async {
    print('Page refreshing...');

    setState(() {
      futureFiles = FirebaseStorage.instance.ref('files').listAll();
      print('Status updated...');
    });

    build(context);
    // ListFiles();
    print('Page refreshed...');
  }
}

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

  @override
  State<AddButton> createState() => _AddButtonState();
}

class _AddButtonState extends State<AddButton> {
  PlatformFile? pickedFile;
  UploadTask? uploadTask;

  late Future<ListResult> futureFiles;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(20.0),
          child: FloatingActionButton(
            backgroundColor: const Color(0xFFFF1D1D),
            foregroundColor: Colors.white,
            onPressed: () async {
              addFile();
            },
            child: const Icon(Icons.add),
          ),
        ),
      ],
    );
  }

  Future addFile() async {
    final result = await FilePicker.platform.pickFiles();
    if (result == null) return;

    setState(() {
      pickedFile = result.files.first;
    });

    uploadFile();
  }

  Future uploadFile() async {
    final path = 'files/${pickedFile!.name}';
    final file = File(pickedFile!.path!);
    final ref = FirebaseStorage.instance.ref().child(path);
    final _ListFilesState Listfile = new _ListFilesState();

    setState(() {
      uploadTask = ref.putFile(file);
    });

    setState(() {
      uploadTask = null;
    });

    if (pickedFile != null) {
      addtoFirestore();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const Text('File uploaded successfully!'),
              const Spacer(
                flex: 2,
              ),
              TextButton(
                onPressed: () => Listfile.onRefresh(),
                child: const Text(
                  'Refresh',
                  style: TextStyle(color: Colors.blue),
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

`
这是我得到的响应消息时,snackbar的刷新按钮被点击。
enter image description here此实施是否正确?感谢您抽出宝贵时间。

相关问题