我是 Flutter 的新手,在我短暫的網上搜索中沒有發現什么成功的答案,這就是發這個帖子的原因。
以下是相關的代碼:
//`myList`有可能為空。
children: widget.myList?.map((item) {
return Text("Hi.") 。
}).toList()。
我試圖在我的有狀態的widget中,在一個column的children:屬性中回圈處理一個List<String>?錯誤。
Dart告訴我,我不能在List<String>?上進行map,并建議我使用myList?.map代替。
然而,當我這樣做時,現在的問題是,children:期望一個List<Widget>,因此不能接受一個List<Widget>?...
我似乎陷入了迂回的錯誤中,但不知為何,我覺得解決方案很簡單。我還在學習null-safety的知識。
所以我想說的是:
我如何在一個可能為空的小部件串列和一個期望不為空的小部件串列的屬性之間進行協調?
解決方案
children: myList?.map((e) => Text(e)).toList() ? [],
uj5u.com熱心網友回復:
如果你的List是List<Widget>?,你可以簡單地添加一個null檢查,像這樣:
children: _widgets?.map((item) => item).toList() ? [Text('List was null')]。
如果你的List是List<Widget?>?你可以把它改為:
children: _widgets?.map((item) => item ? Text('widget was null')).toList() ?? [Text('List was null')]。
如果你想在一個List<String?>里面映射一個Column
Column(
子女。_strings.map((e) => Text(e ? ? 'String was null') .toList(),
)
OR
Column(
children: _strings.map((e) => e == null ? Text('was null') : Text(e)).toList( ),
)
如果你的List是List<String>?
Column(
兒童。_strings?.map((e) =>Text(e)).toList() ? [Text('The list was null')] 。
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311657.html
標籤:
下一篇:Python。回圈嵌套字典的問題
