Skip to content

Instantly share code, notes, and snippets.

@mercykip
Created September 2, 2021 07:40
Show Gist options
  • Select an option

  • Save mercykip/eed792f5b9c99843150e415587a65e39 to your computer and use it in GitHub Desktop.

Select an option

Save mercykip/eed792f5b9c99843150e415587a65e39 to your computer and use it in GitHub Desktop.
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class FileUpload extends StatefulWidget {
FileUpload({Key? key}) : super(key: key);
@override
_FileUploadState createState() => _FileUploadState();
}
class _FileUploadState extends State<FileUpload> {
firebase_storage.FirebaseStorage storage =
firebase_storage.FirebaseStorage.instance;
File? file;
selectFile() async {
final result = await FilePicker.platform.pickFiles(allowMultiple: false);
if (result == null) return;
final path = result.files.single.path;
setState(() => file = File(path));
}
Future uploadFile() async {
if (file == null) return;
final fileName = basename(file!.path);
final destination = 'files/$fileName';
try {
final ref = firebase_storage.FirebaseStorage.instance
.ref(destination)
.child('file/');
await ref.putFile(file!);
final urlString = ref.getDownloadURL();
print('Url $urlString');
return urlString;
} catch (e) {
// e.g, e.code == 'canceled'
}
}
@override
Widget build(BuildContext context) {
final fileName = file != null ? basename(file!.path) : 'No File Selected';
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child:
TextButton(onPressed: selectFile, child: Text('Select File')),
),
Text(
fileName,
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
Container(
child:
TextButton(onPressed: uploadFile, child: Text('Upload File')),
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment