按下按钮时如何显示与FutureBuilder的对话框?



我使用 FutureBuilder 上传了一张图片 FirebaseStorage,当我按下上传按钮时,我想显示一个等待对话框。图像在FireStorage上成功上传,但没有任何显示。我的代码出了什么问题?我认为未来构建器返回小部件并按下按钮无效。也许是问题所在。或者我称FutureBuilder为错误的方式。您对我的错误代码有什么提示或建议吗?

这是我的代码;


Widget buildBody(BuildContext context) {
return new SingleChildScrollView(
child: new Column(
children: [
new SizedBox(
width: double.infinity,
child: new RaisedButton(
child: new Text('Upload'),
onPressed:  () {
futureBuilder();
},
),
),
],
),
);
}
Future mediaUpload() async {
final fileName = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg';
final StorageReference storage = FirebaseStorage.instance.ref().child(fileName);
final StorageUploadTask task = storage.putFile(_image);
return task.future;
}
Widget futureBuilder() {
return new FutureBuilder(
future: mediaUpload(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
print('ConnectionState.none');
return new Text('Press button to start.');
case ConnectionState.active:
print('ConnectionState.active');
return new Text('');
case ConnectionState.waiting:
waitingDialog(context);
return waitingDialog(context);
case ConnectionState.done:
print('ConnectionState.done');
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
print(snapshot.data.downloadUrl);
Navigator.of(context).pushReplacementNamed('home');
return new Text('Result: ${snapshot.data.downloadUrl}');
}
},
);
}
waitingDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new Center(
child: new SizedBox(
width: 40.0,
height: 40.0,
child: const CircularProgressIndicator(
value: null,
strokeWidth: 2.0,
),
),
);
},
);
}

我不是 100% 确定为什么FutureBuilder不起作用。但我有一个猜测。在上面的例子中,FutureBuilder没有附加到widgetTree(screen(。未附加表示从FutureBuilder返回的值不会显示在屏幕中。在这种情况下,Text根据未附加到屏幕的snapshot.connectionState返回。

解决方法: (我测试过,它有效,你能验证一下吗(

futureBuilder(BuildContext context) {
mediaUpload().then((task) {          // fire the upload
Navigator.of(context).maybePop();  // remove the dialog on success upload
});                                  // we can use task(which returned from
// mediaUpload()) to get the values like downloadUrl.
waitingDialog(context);             // show the spinner dialog
}

相关内容

  • 没有找到相关文章

最新更新