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

Flutter开发OtpPage页面报错getter 'context'未定义如何解决

报错原因

build方法里的context是该方法的局部参数,不是OtpPage类的全局成员,你在类的独立私有方法_textFieldOTP中直接调用,自然找不到这个变量。
额外说明:只有StatefulWidget对应的State类才内置了context属性可以在类内全局访问,StatelessWidget本身不持有全局context,所有context依赖的操作都需要通过方法参数传入可用的context。
另外你原有代码里的焦点切换逻辑写反了,会导致输入中间位验证码时焦点来回跳,修复时会一并处理。

修复步骤
  • 给_textFieldOTP方法增加BuildContext类型的必填参数,同时补全原来没加必填标记的last参数
  • 所有调用_textFieldOTP的位置,把build方法拿到的context传进去
  • 修正焦点回退的判断逻辑:只有用户删除输入(内容为空)且不是第一个输入框时,才触发上一个焦点的跳转,不要在输入内容时触发回退
修复后的核心代码

首先修改_textFieldOTP方法定义和内部逻辑:

// 原方法为Widget _textFieldOTP({required bool first, last})
Widget _textFieldOTP({required BuildContext context, required bool first, required bool last}) {
  return Container(
    height: 60,
    width: 52,
    child: AspectRatio(
      aspectRatio: 1.0,
      child: TextField(
        autofocus: true,
        onChanged: (value) {
          if(value.length == 1 && last == false){
            FocusScope.of(context).nextFocus();
          }
          // 原判断为value.length == 1 && first == false,逻辑错误已修正
          if(value.isEmpty && first == false){
            FocusScope.of(context).previousFocus();
          }
        },
        showCursor: false,
        readOnly: false,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        maxLength: 1,
        decoration: InputDecoration(
          counter: Offstage(),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 2, color: Colors.black),
            borderRadius: BorderRadius.circular(6),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(width: 2, color: Colors.purple),
            borderRadius: BorderRadius.circular(6),
          ),
        ),
      ),
    ),
  );
}

再修改Row中调用输入框组件的部分:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    _textFieldOTP(context: context, first: true, last: false),
    _textFieldOTP(context: context, first: false, last: false),
    _textFieldOTP(context: context, first: false, last: false),
    _textFieldOTP(context: context, first: false, last: false),
    _textFieldOTP(context: context, first: false, last: true),
  ],
),

改完后不仅会消除context找不到的报错,焦点切换逻辑也能正常运行:输入完1位验证码自动跳转到下一个输入框,删除完当前框内容自动跳回上一个输入框。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:03:19