Flutter类型不匹配报错:Object无法赋值给List<dynamic>
解决Dart类型不匹配报错:Object无法赋值给List
报错信息
A value of type 'Object' can't be assigned to a variable of type 'List'
相关代码
调用处代码:
void _addBook(BuildContext context) async { List<dynamic> result = await _showWindow(context, "Enter the book name") ?? []; }
_showWindow函数代码:
Future<String?> _showWindow(BuildContext context, String title) { return showDialog<String>( context: context, builder: (context) { String result = ""; return AlertDialog( title: Text(title), content: TextField( keyboardType: TextInputType.text, onChanged: (String inputText) { result = inputText; }, ), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context, ""); }, child: Text("Cancel")), TextButton( onPressed: () { Navigator.pop(context, result.trim()); }, child: Text("Approve")) ], ); }); }
问题原因
_showWindow函数返回的是Future<String?>类型(用户输入的单个字符串或空值),但你试图将其赋值给List<dynamic>类型的变量,直接导致类型不匹配报错。
解决办法
根据实际业务需求选择以下任意一种方案:
- 匹配返回值类型(推荐)
将变量类型改为String?,和函数返回值类型保持一致:
void _addBook(BuildContext context) async { String? result = await _showWindow(context, "Enter the book name") ?? ""; }
- 将结果转为列表(如果需要)
如果业务逻辑确实需要把结果存入列表,先获取字符串再创建列表:
void _addBook(BuildContext context) async { String? bookName = await _showWindow(context, "Enter the book name") ?? ""; List<dynamic> result = [bookName]; }
内容的提问来源于stack exchange,提问作者gurkan stack
相关产品推荐
相关产品推荐

