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

Flutter实现复选框勾选时文本添加删除线的方法咨询

How to Add Strikethrough Style When Task is Marked Done

Hey Amanda, great question! Since your toggleDone method is already correctly updating the task's status and notifying listeners to trigger a UI rebuild, the solution lies in dynamically applying a TextStyle based on the task's status property in your UI layer.

Here's how to implement it step by step:

1. Dynamically Set TextDecoration in Your Text Widget

When building each task item, use the task.status boolean to conditionally apply the strikethrough (and optionally adjust color for better visual feedback):

// Example using ListTile (adjust based on your actual UI setup)
ListTile(
  leading: Checkbox(
    value: task.status,
    onChanged: (newValue) {
      // Call your existing toggleDone method
      yourViewModel.toggleDone(task, newValue!);
    },
  ),
  title: Text(
    task.title,
    style: TextStyle(
      // Add strikethrough only when task is marked done
      decoration: task.status ? TextDecoration.lineThrough : TextDecoration.none,
      // Optional: Dim the text color for completed tasks
      color: task.status ? Colors.grey.shade600 : Colors.black87,
      fontSize: 16,
    ),
  ),
)

2. Optional: Reuse the Style with a Helper Method

If you use this style in multiple places, extract it into a helper method to keep your code clean:

TextStyle getTaskTextStyle(bool isCompleted) {
  return TextStyle(
    decoration: isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
    color: isCompleted ? Colors.grey.shade600 : Colors.black87,
    fontSize: 16,
    fontWeight: isCompleted ? FontWeight.w400 : FontWeight.w500,
  );
}

// Then use it in your Text widget:
Text(
  task.title,
  style: getTaskTextStyle(task.status),
)

Why This Works

Your toggleDone method already does the heavy lifting:

  • It updates the task.status to the new value
  • It calls notifyListeners(), which tells your UI to rebuild with the latest task state

When the UI rebuilds, the Text widget checks the updated task.status and applies the correct style automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:42:29