[英]How to pass variable content to a parameter value in dart/flutter?
[英]How to pass the changed value of a variable from a method to a condition in Flutter/Dart?
我像這樣檢查互聯網訪問:
我在主頁上的代碼:
class _MainWidgetState extends State<MainWidget> {
CheckUserConnection _checkUserConnection = CheckUserConnection();
InternetDialogHandler _internetDialogHandler = InternetDialogHandler();
bool? _internetAvailable;
...
void checkNet() async{
_internetAvailable = await
_checkUserConnection.checkInternetAvailability();
setState((){});
}
我的代碼在不同的頁面上,因為它在多個屏幕上使用。
class CheckUserConnection {
Future checkInternetAvailability() async {
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
}
}
這很好用,但是當 checkNet() 在具有 _internetAvailable 的條件之前檢查 Internet 可用性時會出現問題。
尤其是:
GradientButton(label: 'Continue Game', onTap: () {
checkNet();
_loadData();
return _internetAvailable == true ?
{Navigator.push(
context,
MaterialPageRoute(builder: (context) => Game(
listCount: _listCount, assetPath: assetPath ///What I want to pass
)),
)}
:
_internetDialogHandler.showInternetDialog(context);
}),
情況如下。 首先,有互聯網接入。 分別為 _internetAvailable=true。
然后我特地關閉了上網並按下按鈕。 checkNet() 將檢查 _internetAvailable 並將此變量設置為 true。 因此,滿足條件。 這是錯誤的。
但是當我下次單擊該按鈕時,_internetAvailable 會采用正確的值,即 false。
我的問題如下。 我在哪里犯錯? 我希望 checkNet() 第一次正確更改 _internetAvailable 的值。
是的,問題不在於互聯網訪問。 作為實驗,我使用了其他變量。 例如,_isFirstLoad = true。 情況是一樣的。 第一次按下按鈕時,變量的值不會改變。
像這樣使用checkInternetAvailability()
class CheckUserConnection {
Future<bool> checkInternetAvailability() async {
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
} on SocketException catch (_) {
return false;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.