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

Flutter登录页TextField的OnChange报"Invalid constant value"错误求助

解决Flutter登录页中TextField onChange回调的"Invalid constant value"错误

错误原因

你给Column的children加了const修饰,意味着列表里的所有Widget必须是编译时常量。但TextField的onChanged是动态的函数回调(会修改外部变量email),不属于编译时常量,因此触发"Invalid constant value"错误。

解决方案

不要给整个children列表加const,但可以给列表里无需动态变化的Widget单独添加const修饰——这样既解决错误,又能保留const的性能优化效果,消除"Prefer const with constant constructors"警告。

修改后的代码如下:

import 'package:flutter/material.dart';

String email = '';
String password = '';

class Login extends StatelessWidget {
  const Login({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(20.0),
      padding: const EdgeInsets.all(10.0),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          // 移除children的const修饰
          children: <Widget>[
            // 静态文本组件保留const
            const Padding(
              padding: EdgeInsets.all(30.0),
              child: Text('Welcome to the log in'),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextField(
                obscureText: true,
                // 静态的InputDecoration保留const
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'email',
                ),
                onChanged: (text) {
                  email = text;
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: TextField(
                obscureText: true,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'password',
                ),
                // 补充密码的onChanged回调
                onChanged: (text) {
                  password = text;
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者César Sotillo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:01:11