[英]How do I convert 'Future<String?>' to 'Future<String>?' in Flutter?
所以基本上我正在使用network_info_plus包來讀取設備當前連接的 Wifiname。 我想使用FutureBuilder
從await info.getWifiName();
獲取未來 . 問題是該方法返回一個Future<String?>
。 將其轉換為Future<String>?
?
例如
NetworkInfo info = NetworkInfo();
...
FutureBuilder<String>(
future: info.getWifiName(), // Error: The argument type 'Future<String?>'
// can't be assigned to the parameter type 'Future<String>?'
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
...
如果你看一下 getWifiName() 函數的內部實現
/// Obtains the wifi name (SSID) of the connected network
///
/// Please note that it DOESN'T WORK on emulators (returns null).
///
/// From android 8.0 onwards the GPS must be ON (high accuracy)
/// in order to be able to obtain the SSID.
Future<String?> getWifiName() {
return _platform.getWifiName();
}
它返回一個 Future<String?> 。 對於 FutureBuilder,您有兩種選擇
這是在 mac 應用程序上運行此代碼的默認顫振應用程序的演示
你可以這樣稱呼它
FutureBuilder<String?>(
future: info.getWifiName(),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You are connected to WIFI ',
),
Text(
'${snapshot.data}',
style: Theme.of(context).textTheme.headline4,
),
],
),
);
}
return const Center(
child: CircularProgressIndicator(),
);
})
或者您可以選擇在使用 FutureBuilder 時不顯式聲明數據類型
FutureBuilder(
future: info.getWifiName(),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You are connected to WIFI ',
),
Text(
'${snapshot.data}',
style: Theme.of(context).textTheme.headline4,
),
],
),
);
}
return const Center(
child: CircularProgressIndicator(),
);
})
請注意,您並沒有真正轉換這里的數據類型,只是說明它並使 FutureBuilder 知道從給定的未來期望什么數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.