Flutter upload file to Firebase storage

33 views Asked by At

Can someone help me please. I want to upload a file to Firebase storage but for some reasons this code doesn't work. Can anyone help me please.

class TestUploadToStorage extends StatefulWidget {
  const TestUploadToStorage({super.key});

  @override
  State<TestUploadToStorage> createState() => _TestUploadToStorageState();
}

class _TestUploadToStorageState extends State<TestUploadToStorage> {
  PlatformFile? testFile;

  Future selectTestFile() async {
    final result = await FilePicker.platform.pickFiles();
    if (result == null) result;
    setState(() {
      testFile = result?.files.first;
    });
  }

  Future uploadTestFile() async {
    final pathTest = "TESTFILE/${testFile!.name}";
    final fileTest = File(testFile!.path!);
    final testRef = FirebaseStorage.instance.ref().child(pathTest);
    testRef.putFile(fileTest);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            if (testFile != null) Text(testFile!.name),
            TextButton(
              onPressed: selectTestFile,
              child: const Text("select TestFile"),
            ),
            TextButton(
                onPressed: uploadTestFile, child: const Text("Test upload"))
          ],
        ),
      ),
    );
  }
}

I'm using Mac M1 and my app is a web App

1

There are 1 answers

0
A-E On

I was facing a similar problem, here's what you should do.

Put await before putFile method.

await testRef.putFile(fileTest);

Although putFile method doesn't return a Future Value which is weird to wait for it, but it worked for me.

Hope it helps you