我正在使用 for 回圈遍歷一個陣列,即“公司”。我想使用“for 回圈”顯示此陣列中的第一個元素,而不必以“公司 [0].name”的方式執行此操作。這是我所做的作業,但我需要將它們用于回圈。
child: Column(
children: < Widget > [
// for (var item in companies)
companies.length > 0 ?
Text(
'${companies[0].name}'.toUpperCase(), // how can i replace this using the for loop
style: TextStyle(
color: AppColor.white,
),
) :
Text('No Company Assigned '),
],
),
uj5u.com熱心網友回復:
您可以使用行內函式來創建回圈。不過,我建議在這里保持簡單的邏輯。大多數人更喜歡在您的情況下使用地圖,如@pskink 在評論部分描述的那樣。
Column(
children: [
() {
// do the thing you want and return
return companies.isEmpty
? Text('No Company Assigned ')
: Text(companies.first.toUpperCase());
}(),
],
),
uj5u.com熱心網友回復:
您可以使用集合包中的mapIndexed或forEachIndexed擴展方法。
import 'package:collection/collection.dart';
item.forEachIndexed((index, element) {
print('index: $index, element: $element');
});
uj5u.com熱心網友回復:
你可以像下面的例子一樣使用 ListBuilder,如果它的第一個元素回傳你的小部件,否則回傳空容器。
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];
ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return index == 0 ? Container(
height: 50,
color: Colors.amber[colorCodes[index]],
child: Center(child: Text('Entry ${entries[index]}')),
): Container();
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368689.html
上一篇:在已排序的陣列中查找重復數字
下一篇:如何處理具有不同引數的派生類
