我有一個帶有底部導航欄的應用程式:
Widget build(BuildContext context) {
print("current tab");
print(currentTab?.index); //<-- It's work!! -->
return BottomNavigationBar(
selectedItemColor: _colorTabMatching(currentTab!),
selectedFontSize: 13,
unselectedItemColor: Colors.grey,
type: BottomNavigationBarType.fixed,
currentIndex: currentTab?.index, //<-- does not work!! -->
items: [
_buildItem(TabItem.POSTS),
_buildItem(TabItem.ALBUMS),
_buildItem(TabItem.TODOS),
],
onTap: (int index) => onSelectTab!(
TabItem.values[index]
)
);
錯誤:
引數型別“int?” 不能分配給引數型別“int”。
現在我需要傳遞索引,但我看到一個錯誤。為什么?

uj5u.com熱心網友回復:
currentIndex不采用可為空的 int。
做currentTab?.index意味著它正在接受空值。您可以在 null 情況下將默認值提供為 0,例如,
currentIndex: currentTab?.index?? 0
更多關于null-safety和currentIndex
uj5u.com熱心網友回復:
我來自 C# 背景,僅根據錯誤訊息判斷,基本上發生的事情是,屬性currentIndex應該是 type int。您的代碼的問題在于currentTab它的型別TabItem?意味著可為空的 TabItem。這意味著它可以是null或TabItem object。使用語法currentTab?.index基本上是說:“如果 currentTab 為 null,則回傳 null。如果它不為 null,則回傳索引值。”。Dart 語法與 C# 非常相似,我檢查了這段代碼是否可以作業:
currentIndex: currentTab?.index ?? 0
基本上這段代碼的作用是:“如果 currentTab 為空,則回傳值 0。如果它不為空,則回傳索引值。”。看到區別了嗎?您基本上必須手動處理currentTab等于的情況null。
免責宣告:我沒有嘗試此代碼,但是正如我所說,C# 和 Dart 是相似的(就語法而言),我在互聯網上仔細檢查了 Dart 確實提供了這些語法功能
編輯:或者您可以在渲染之前使用某種 Flutter 方式處理 currentTab 為空,但是,正如我之前所說,我不知道 Dart/Flutter。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/497907.html
