問題描述
如何將數據數組轉換為在顫振/飛鏢中展開或折疊的小部件列表? (How to convert an array of data to a list of widgets with expand or fold in flutter/dart?)
對自己沒有解決問題感到非常沮喪,但最終放棄了。我有一個字段數組,每個字段都是帶有標題和值的地圖。我想遍歷它並創建一個文本小部件列表以及它們之間的一些填充。我嘗試了以下操作:
fields.expand((field)=>
[ Text(field['title']),
Padding(padding: const EdgeInsets.only(bottom: 4.0))
]
).toList()
但這給出了以下錯誤:
type 'List<dynamic>' is not a subtype of type 'List<Widget>'
我嘗試在 expand
> 但後來我得到:
type 'MappedListIterable<Map<String, String>, dynamic>' is not a subtype of type 'List<Widget>'
我也嘗試在 expand(
之後添加 但後來我得到:
type '<Widget>(dynamic) => List<Widget>' is not a subtype of type '(Map<String, String>) => Iterable<dynamic>' of 'f'
不知道還能做什麼。我怎麼能強迫它意識到這是一個小部件列表?我也嘗試過使用 fold,但遇到了類似的打字問題。
參考解法
方法 1:
I think what you're looking for is .map()
, but there's a cleaner way to do it :
items: [
for(var field in fields)
...[
Text(field['title']),
Padding(padding: const EdgeInsets.only(bottom: 4.0)),
]
]
Make sure your minimum SDK version is 2.6.0 or above in the pubspec.yaml
方法 2:
As I said in my comment, one of your solutions appears to should have work, but since it didn't I'm providing an alternate solution.
You can use a for‑each
loop to "manually" create an output List
that you can pass to your Column
widget. Ex.
List<Widget> columnList = List();
for(Map field in fields) {
columnList.add(Text(field['title']);
columnList.add(Padding(padding: const EdgeInsets.only(bottom: 4.0)));
}
方法 3:
As @christopher‑moore noted, adding <Widget>
after expand
does work. The reason I thought it was not working was that I kept getting the error, but for a different place where I still had the same statement but without that addition.
(by shaimo、MickaelHrndz、Christopher Moore、shaimo)