假设您有一个来自API字符串列表,现在您希望在DropdownButton中显示该列表,假设您的列表如下所示
homepage_categories": [
{
"id": 1,
"name": "Electronics",
"slug": "electronics",
"icon": "fas fa-anchor",
"image": "uploads/custom-images/electronics-2022-11-19-02-48-28-5548.png"
},
{
"id": 2,
"name": "Game",
"slug": "game",
"icon": "fas fa-gamepad",
"image": "uploads/custom-images/game-2022-11-19-02-48-48-6382.png"
},
{
"id": 3,
"name": "Mobile",
"slug": "mobile",
"icon": "fas fa-mobile-alt",
"image": "uploads/custom-images/mobile-2022-11-19-02-49-20-2538.png"
},
{
"id": 4,
"name": "Lifestyle",
"slug": "lifestyle",
"icon": "fas fa-home",
"image": "uploads/custom-images/lifestyle-2022-11-19-02-49-38-3139.png"
},
]
从这个API你可以很容易地获取.
因此,问题是如何将默认/初始值(如“选择类别”或其他值)分配到该列表中
我试过了...
late List<CategoryModel> category;
late String value;
@override
void initState() {
category = context.read<CategoryBrandCubit>().categoryBrandModel.category;
value = category.first.id.toString();
super.initState();
}
DropdownButton<String>(
hint: const Text('Select Status'),
isExpanded: true,
icon: const Icon(Icons.keyboard_arrow_down_rounded),
underline: const SizedBox(),
value: value,
onChanged: (String? val) {
value = val!;
bloc.add(StoreProductEventCategory(value));
print('catVal: $value');
},
items: category
.map(
(e) => DropdownMenuItem<String>(
value: e.id.toString(),
child: Text(e.name),
),
)
.toList(),
),
2条答案
按热度按时间knpiaxh11#
试试这个:
bn31dyow2#
DropdownButton
的默认值对应于value
字段。如果我们看一下代码,我们会发现您分配了值,但它是空的:你要做的就是给
value
赋一个初始值,你可以这样做:value = homepage_categories[0].name
如果您看一下官方的flutter文档,您还可以看到value字段的描述如下:
value → T?:当前选定下拉菜单项的值。
您可以阅读更多关于它的内容here并查看完整的示例。