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

首次学习Flutter:返回ListView组件时应用崩溃求助

问题分析与修复

你的代码崩溃的核心原因是错误调用了字符串转小写的方式:

错误点

在ListView的ListTile中,你写了hist.asLowerCase,但Dart的字符串类型并没有名为asLowerCase的属性,正确的转小写操作是调用toLowerCase()方法(注意末尾的括号)。这个语法错误会导致Widget渲染时抛出异常,直接引发应用崩溃。

而第二个能运行的代码里,并没有使用这个错误的属性调用,所以可以正常执行。

修复后的代码

将hist.asLowerCase替换为hist.toLowerCase()即可:

class HistoryList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();

    if (appState.history.isEmpty) {
      return Center(
        child: Text('No history yet.'),
      );
    } else {
      return ListView(
        children: [
          for (var hist in appState.history)
            ListTile(
              leading: Icon(Icons.favorite),
              title: Text(hist.toLowerCase()),
            ),
        ],
      );
    }
  }
}

额外提示

如果appState.history中的元素不是字符串类型,还需要先将其转为字符串再调用toLowerCase(),比如hist.toString().toLowerCase(),不过从你第二个代码里的appState.history.firstOrNull.toString()来看,hist应该本身就是字符串,所以直接替换即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:53:13