gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:46:00 26 4
gpt4 key购买 nike

我使用 FutureBuilder 上传一张图片 FirebaseStorage,当我按下上传按钮时,我想显示一个等待对话框。图像已成功上传到 FireStorage,但未显示任何内容。我的代码有什么问题?我认为 FutureBuilder 返回 Widget 并按下按钮无效。也许这是问题所在。或者我以错误的方式调用 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
}

关于firebase - 按下按钮时如何显示与 FutureBuilder 的对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52126546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com