Flutter中List<Map<String,dynamic>>转DropdownMenuItem类型不匹配问题
问题根源
你的代码存在两个核心问题:
FullCurrencyList类并非实体类,只是包含静态Map列表的容器,无法直接作为DropdownMenuItem的value类型使用。DropdownButton<String>声明的泛型类型是String,但生成的items却是List<DropdownMenuItem<FullCurrencyList>>,类型完全不匹配,导致报错。
步骤1:重构FullCurrencyList为实体类
先把currencies.dart中的类改成真正的实体类,每个实例对应一个货币:
class FullCurrencyList { final String code; final String name; FullCurrencyList({required this.code, required this.name}); // 静态货币列表,存放实体类实例 static final List<FullCurrencyList> currencies = [ FullCurrencyList(code: "USD", name: "United States Dollar"), // 可添加更多货币 ]; }
步骤2:选择适配方案
根据业务需求,任选以下一种方案修复类型不匹配问题:
方案一:用FullCurrencyList作为DropdownButton的泛型类型
适合需要获取完整货币信息的场景,调整页面代码如下:
import 'package:flutter/material.dart'; import 'package:brain/util/currencies.dart'; class Page3 extends StatefulWidget { @override State<StatefulWidget> createState() => _Page3State(); } class _Page3State extends State<Page3> { FullCurrencyList? _valCurrency; List<FullCurrencyList> _currencyList = FullCurrencyList.currencies; @override Widget build(BuildContext context) { return Column( children: <Widget>[ Container( child: Text("Please, select your currency:"), ), Row( children: <Widget>[ Container( child: Text("Currency:"), ), Container( child: DropdownButton<FullCurrencyList>( borderRadius: BorderRadius.circular(10), hint: const Text("Select"), value: _valCurrency, items: _currencyList.map<DropdownMenuItem<FullCurrencyList>>((FullCurrencyList value) { return DropdownMenuItem<FullCurrencyList>( value: value, child: Text('${value.name} ${value.code}'), ); }).toList(), onChanged: (FullCurrencyList? value) { setState(() { _valCurrency = value; }); }, ), ), ], ), ], ); } }
方案二:保持DropdownButton类型
适合只需要货币编码(如USD)的场景,调整页面代码如下:
import 'package:flutter/material.dart'; import 'package:brain/util/currencies.dart'; class Page3 extends StatefulWidget { @override State<StatefulWidget> createState() => _Page3State(); } class _Page3State extends State<Page3> { String? _valCurrency; List<FullCurrencyList> _currencyList = FullCurrencyList.currencies; @override Widget build(BuildContext context) { return Column( children: <Widget>[ Container( child: Text("Please, select your currency:"), ), Row( children: <Widget>[ Container( child: Text("Currency:"), ), Container( child: DropdownButton<String>( borderRadius: BorderRadius.circular(10), hint: const Text("Select"), value: _valCurrency, items: _currencyList.map<DropdownMenuItem<String>>((FullCurrencyList value) { return DropdownMenuItem<String>( value: value.code, child: Text('${value.name} ${value.code}'), ); }).toList(), onChanged: (String? value) { setState(() { _valCurrency = value; }); }, ), ), ], ), ], ); } }
内容的提问来源于stack exchange,提问作者user3132858
相关产品推荐
相关产品推荐

