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

Flutter中Text组件引用变量报Not a constant expression错误如何解决

问题解决与实现方案

报错修复

Error: Not a constant expression 错误的原因是你给 SizedBox 添加了 const 修饰符,const 要求其构造的Widget内部所有值都为编译期常量,但grabItem.title是运行时从列表读取的动态值,不符合常量要求,直接删除SizedBox前的const关键字即可解决该错误。

全列表卡片实现方案

要实现遍历列表生成所有条目卡片的需求,推荐使用ListView.builder组件,相比手动拼接Column性能更高,适配任意长度的列表。完整优化后的代码如下:

import 'package:flutter/material.dart';

//ItemData used in addnew.dart
class ItemData {
  final String id;
  final String score;
  final String title;
  final String description;

  ItemData({
    required this.id,
    required this.score,
    required this.title,
    required this.description});
}

//Dummy list of items
final itemList = [
  ItemData(
      id: 'one',
      score: '30',
      title: 'Title One',
      description: 'mock description'),
  ItemData(
      id: 'two',
      score: '10',
      title: 'Title Two',
      description: 'mock description'),
  ItemData(
      id: 'three',
      score: '20',
      title: 'Title Three',
      description: 'mock description'),
];

// 按分数倒序排序
void sortList() {
  itemList.sort((item1, item2) => int.parse(item2.score).compareTo(int.parse(item1.score)));
}

class ListPage extends StatefulWidget {
  const ListPage({Key? key}) : super(key: key);

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
  @override
  void initState() {
    super.initState();
    // 页面初始化时执行一次排序即可,不需要每次build都排序
    sortList();
  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar(
        title: const Text('List View',
          style: TextStyle(
            letterSpacing: 2.0,
          ),
        ),
        centerTitle: true,
      ),
      // 用ListView.builder遍历渲染所有卡片,性能更优
      body: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 16),
        itemCount: itemList.length,
        itemBuilder: (context, index) {
          final currentItem = itemList[index];
          return Center(
            child: ItemCard(item: currentItem),
          );
        },
      ),
    );
  }
}

// 通用卡片组件,接收ItemData参数实现复用
class ItemCard extends StatelessWidget {
  final ItemData item;
  const ItemCard({Key? key, required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        splashColor: Colors.blue.withAlpha(30),
        onLongPress: (){
          print('长按了卡片:${item.title}');
        },
        child: SizedBox(
          width: 300,
          height: 100,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(item.title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),),
                const SizedBox(height: 4,),
                Text('分数:${item.score}'),
                const SizedBox(height: 4,),
                Text(item.description, style: const TextStyle(color: Colors.grey),)
              ],
            ),
          ),
        ),
      ),
    );
  }
}

核心优化点

  • 调整排序逻辑:将排序操作放到页面初始化阶段执行,避免build方法重复触发排序导致性能损耗,同时将字符串类型的score转为数字后比较,避免字符串排序的逻辑错误
  • 通用卡片封装:把卡片组件改为可接收ItemData参数的通用组件,复用性更高,代码更易维护
  • 列表渲染优化:用ListView.builder替代固定的Column组件,支持长列表的懒加载,性能更优
  • 移除错误const修饰:删除了动态SizedBox的const标识,解决常量校验错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:54:04