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

Flutter报错:预期类型为'Widget?',实际得到'String'求解决

问题解决:Expected a value of type 'Widget?', but got one of type 'String'

错误原因

ListTile的title和subtitle参数要求传入Widget类型,但代码中直接传递了字符串值(_thisItem["title"]和_thisItem["body"]是String类型),类型不匹配触发了这个错误。

另外,fetchItems函数的类型处理存在隐患:jsonDecode解析后的数据实际是List<Map<String, dynamic>>,直接用cast<Map>不够严谨,可能引发后续类型问题。

修复步骤

1. 修正ListTile的参数类型

把字符串用Text组件包裹,Text是标准Widget类型,符合参数要求:

return ListTile(
  title: Text(_thisItem["title"]),
  subtitle: Text(_thisItem["body"]),
);

2. 优化数据解析的类型准确性

将fetchItems的返回类型和内部类型改为更精准的List<Map<String, dynamic>>,避免类型转换风险:

Future<List<Map<String, dynamic>>> fetchItems() async {
  List<Map<String, dynamic>> items = [];

  http.Response response =
      await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));

  if (response.statusCode == 200) {
    String jsonString = response.body;
    // 直接指定解析后的类型,无需cast
    items = List<Map<String, dynamic>>.from(jsonDecode(jsonString));
  }

  return items;
}

同时同步更新PostList中Future的类型定义:

final Future<List<Map<String, dynamic>>> _futurePosts = HTTPHelper().fetchItems();

// 后续使用时对应修改类型
List<Map<String, dynamic>> _posts = snapshot.data!;
Map<String, dynamic> _thisItem = _posts[index];

完整修复后的PostList代码

class PostList extends StatelessWidget {
  PostList({super.key});

  final Future<List<Map<String, dynamic>>> _futurePosts = HTTPHelper().fetchItems();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Posts"),
      ),
      body: FutureBuilder(
        future: _futurePosts,
        builder: ((context, snapshot) {
          if (snapshot.hasError) {
            return Center(
                child: Text("Some error has occured ${snapshot.error}"));
          }
          if (snapshot.hasData) {
            List<Map<String, dynamic>> _posts = snapshot.data!;
            return ListView.builder(
                itemCount: _posts.length,
                itemBuilder: ((context, index) {
                  Map<String, dynamic> _thisItem = _posts[index];
                  return ListTile(
                    title: Text(_thisItem["title"]),
                    subtitle: Text(_thisItem["body"]),
                  );
                }));
          }
          return const Center(child: CircularProgressIndicator());
        }),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:00:59