我使用FutureBuilder上传了FirebaseStorage图像,当我按下上传按钮时,我想显示一个等待对话框。在FireStorage上成功上传图片但没有显示任何内容。我的密码怎么了?我认为FutureBuilder返回Widget并按下按钮void。也许是问题所在。或者我以错误的方式调用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(屏幕)。未附加意味着从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
}