You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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>类型的变量,直接导致类型不匹配报错。

解决办法

根据实际业务需求选择以下任意一种方案:

  1. 匹配返回值类型(推荐)
    将变量类型改为String?,和函数返回值类型保持一致:
void _addBook(BuildContext context) async {
    String? result = await _showWindow(context, "Enter the book name") ?? "";
}
  1. 将结果转为列表(如果需要)
    如果业务逻辑确实需要把结果存入列表,先获取字符串再创建列表:
void _addBook(BuildContext context) async {
    String? bookName = await _showWindow(context, "Enter the book name") ?? "";
    List<dynamic> result = [bookName];
}

内容的提问来源于stack exchange,提问作者gurkan stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:42:38