'error: Undefined name 'uploadTask'. Flutter error
I am integrating file uploading system in my flutter project using firebase. While making progress indicator I am getting undefined name 'uploadTask' error.
In this project we can upload file,image and many more to firebase and simultaneously view at the same time.
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future selectFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
}
Future uploadFile() async {
final path = 'files/${pickedFile!.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
uploadTask = ref.putFile(file);
final snapshot = await uploadTask!.whenComplete(() => null);
final urlDownload = await snapshot.ref.getDownloadURL();
print('Download link: $urlDownload');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
if (pickedFile != null)
Expanded(
child: Container(
color: Colors.blue[100],
child: Center(
child: Image.file(
File(pickedFile!.path!),
width: double.infinity,
fit: BoxFit.cover,
),
),
),
),
SizedBox(
height: 32,
),
ElevatedButton(
onPressed: selectFile,
child: const Text(
'Select File',
),
),
ElevatedButton(
onPressed: uploadFile,
child: const Text(
'Upload File',
),
),
buildProgress(),
],
),
),
),
);
}
}
Widget buildProgress() => StreamBuilder<TaskSnapshot>(
stream: uploadTask?.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey,
color: Colors.green,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()}%',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|