如何在Flutter中侦听(StorageUploadTask)Firebase上传成功事件



我想监听firebase uploadsuccess事件,这样我就可以向用户确认特定事件的完成。

如何聆听成功事件

在调试控制台中,我得到了以下信息。

I/flutter (22734): EVENT StorageTaskEventType.progress
I/flutter (22734): EVENT StorageTaskEventType.progress
I/flutter (22734): EVENT StorageTaskEventType.progress
I/flutter (22734): EVENT StorageTaskEventType.success

我的上传代码如下所示。

final StorageReference firebaseStoragereference = 
FirebaseStorage
.instance
.ref()
.child('images/myImage1.jpg' );
final StorageUploadTask task = firebaseStoragereference.putFile(sampleImage);

您可以这样做:

final StorageUploadTask uploadTask = ref.putFile(file);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();

为了监听事件,您需要监听事件流&您可以使用StreamBuilder来显示状态。

一个最小的E.g:你可以根据自己的需要修改,比如显示进度条。在您想要显示状态的构建方法中,调用函数-_uploadStatus(task);

String _bytesTransferred(StorageTaskSnapshot snapshot) {
double res = snapshot.bytesTransferred / 1024.0;
double res2 = snapshot.totalByteCount / 1024.0;
return '${res.truncate().toString()}/${res2.truncate().toString()}';
}
Widget _uploadStatus(StorageUploadTask task) {
return StreamBuilder(
stream: task.events,
builder: (BuildContext context, snapshot) {
Widget subtitle;
if (snapshot.hasData) {
final StorageTaskEvent event = snapshot.data;
final StorageTaskSnapshot snap = event.snapshot;
subtitle = Text('${_bytesTransferred(snap)} KB sent');
} else {
subtitle = const Text('Starting...');
}
return ListTile(
title: s.isComplete && s.isSuccessful
? Text(
'Done',
style: detailStyle,
)
: Text(
'Uploading',
style: detailStyle,
),
subtitle: subtitle,
);
},
);
}

@anmol.majhail我改进了你的计算函数,如下所示:

String _bytesTransferred(StorageTaskSnapshot snapshot) {
double res = (snapshot.bytesTransferred / 1024.0) / 1000;
double res2 = (snapshot.totalByteCount / 1024.0) / 1000;
return '${res.toStringAsFixed(2)}/${res2.toStringAsFixed(2)}';
}

有了这个,它会看起来像这样:

3,75/30,32MB发送

此处为Flutter Web:

String _bytesTransferred(fb.UploadTaskSnapshot snapshot) {
double res = (snapshot.bytesTransferred / 1024.0) / 1000;
double res2 = (snapshot.totalBytes / 1024.0) / 1000;
return '${res.toStringAsFixed(2)}/${res2.toStringAsFixed(2)}';
}
Widget _uploadStatus(fb.UploadTask task, String startingText, String doneText,
String uploadingText) {
return StreamBuilder<fb.UploadTaskSnapshot>(
stream: task.onStateChanged,
builder: (BuildContext context, snapshot) {
Widget subtitle;
if (snapshot.hasData) {
final fb.UploadTaskSnapshot snap = snapshot.data;
subtitle = Text('${_bytesTransferred(snap)} MB');
} else {
subtitle = Text(startingText);
}
return ListTile(
title: snapshot.data.state == fb.TaskState.SUCCESS
? Text(doneText)
: Text(uploadingText),
subtitle: subtitle,
);
},
);
}

相关内容

  • 没有找到相关文章

最新更新