Flutter 错误:被调用的构造函数不是 const 构造函数

Wah*_*héb 7 mobile dart mobile-development flutter

我正在开发我的第一个 Flutter 项目,我正在构建一个登录页面,我创建了一个变量来存储 TextFormFieldController 但我收到了上面的错误,因为我删除了构造函数。当我返回此构造函数时,我无法声明一个全局变量来存储 TextFormFieldController。

这是我的代码:(登录页面):

import 'package:flutter/material.dart';

class LoginScreen extends StatelessWidget {
  var loginUsernameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Padding(
        padding: const Edge

Insets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              "Login",
              style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              height: 40,
            ),
            TextFormField(
              decoration: const InputDecoration(
                labelText: "Email Address",
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.email),
              ),
              keyboardType: TextInputType.emailAddress,
            ),
            const SizedBox(
              height: 10,
            ),
    

    TextFormField(
              controller: TextEditingController(),
              obscureText: true,
              decoration: const InputDecoration(
                labelText: "Password",
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.lock),
                suffixIcon: Icon(Icons.remove_red_eye),
              ),
              keyboardType: TextInputType.emailAddress,
            ),
            const SizedBox(
              height: 20,
            ),
            Container(
              width: double.infinity,
              child: MaterialButton(
                onPressed: () {},
                child: const Text(
                  "LOGIN",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
              ),
            )
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这是 main.dart (我收到错误的地方):

import 'package:flutter/material.dart';

import 'login_screen.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LoginScreen(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Diw*_*nsh 34

您需要在MaterialApp之前删除 const :

return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: LoginScreen(),
    );
Run Code Online (Sandbox Code Playgroud)

  • const 关键字需要硬编码的常量值,但您正在构建不是常量的动态小部件,这就是它抛出错误的原因。如果有效,还请标记为已回答。谢谢 (3认同)