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

Flutter获取ColorScheme颜色报错:Undefined name 'context' 求助

解决Flutter中Theme.of(context)调用时"Undefined name 'context'"的错误

错误原因

getTextColor是独立于build方法的类成员方法,无法直接访问build方法内的局部变量context,因此触发未定义名称的错误。

修复方案

方案1:给getTextColor传递BuildContext参数

修改getTextColor的方法签名,添加BuildContext参数,调用时传入build方法里的context:

// 修改getTextColor方法
Color getTextColor(String buttonText, BuildContext context) {
  switch (buttonText) {
    case '+':
    case '-':
    case '⨯':
    case '÷':
    case '=':
      return Colors.red;
    case 'AC':
    case '<':
      return Colors.red;
    default:
      return Theme.of(context).colorScheme.secondary;
  }
}

// 在build方法中调用时传入context
@override
Widget build(BuildContext context) {
  final color = getTextColor(text, context); // 此处传入context
  // 其余代码保持不变...
}

方案2:将getTextColor改为build方法内的局部函数

如果该颜色判断逻辑仅在当前build方法中使用,直接把函数移到build内部,即可直接访问context:

@override
Widget build(BuildContext context) {
  // 定义局部函数,直接访问context
  Color getTextColor(String buttonText) {
    switch (buttonText) {
      case '+':
      case '-':
      case '⨯':
      case '÷':
      case '=':
        return Colors.red;
      case 'AC':
      case '<':
        return Colors.red;
      default:
        return Theme.of(context).colorScheme.secondary;
    }
  }

  final color = getTextColor(text);
  // 其余代码保持不变...
}

额外提示

你的MyDarkTheme类定义末尾缺少闭合括号,建议补上以避免语法错误:

class MyDarkTheme {
  static final dark = ThemeData(
    colorScheme: ColorScheme.fromSwatch().copyWith(
      secondary: Pallete.white,
    ),
  ); // 补上这个闭合括号
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:28:13