嘿,我是 Flutter 的新手,最近我一直在開發一個移動應用程式,它通過 BLE 從 ESP32 接收資料,但我遇到了一個問題,如果我想要求用戶像這樣斷開與設備的連接:
Future<bool> _onWillPop() {
return showDialog(
context: context,
builder: (context) =>
new AlertDialog(
title: Text('Are you sure?'),
content: Text('Do you want to disconnect device
and go back?'),
actions: <Widget>[
new ElevatedButton(
onPressed: () =>
Navigator.of(context).pop(false),
child: new Text('No')),
new ElevatedButton(
onPressed: () {
disconnectFromDevice();
Navigator.of(context).pop(true);
},
child: new Text('Yes')),
],
) ??
false);
}
它給了我錯誤警告:
A value of type 'Future<dynamic>' can't be returned from the method '_onWillPop' because it has a return type of 'Future<bool>'.
The return type 'Object' isn't a 'Widget', as required by the closure's context.
但以我目前的知識,我不知道如何解決我的問題。如果有人可以幫助我,我將非常感激:) 并對任何語法錯誤表示抱歉
uj5u.com熱心網友回復:
Future<T?> showDialog
Future<T?> showDialog<T>(
{required BuildContext context,
required WidgetBuilder builder,
bool barrierDismissible = true,
不需要 return
uj5u.com熱心網友回復:
錯誤表明return型別showDialog不是 bool。相反,您可以只用 await 替換,然后回傳 bool。
下面是您可以放置??的代碼。
Future<bool> _onWillPop(BuildContext context) async {
bool shouldPop = false;
await showDialog(
context: context,
builder: (context) =>
AlertDialog(
title: const Text('Are you sure?'),
content: const Text('Do you want to disconnect device and go back?'),
actions: <Widget>[
ElevatedButton(
onPressed: () {
// shouldPop is already false
},
child: const Text('No')),
ElevatedButton(
onPressed: () async {
await disconnectFromDevice();
Navigator.of(context).pop();
shouldPop = true;
},
child: const Text('Yes')),
],
));
return shouldPop;
}
我對代碼進行了一些更改,以便在您不想彈出時回傳 false,如果要彈出則回傳 true。您可以根據需要更改代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369376.html
