我正在處理我的第一個 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,
),
)
],
),
),
);
}
}
這是 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(),
);
}
}
uj5u.com熱心網友回復:
您需要在MaterialApp之前洗掉 const :
return MaterialApp(
debugShowCheckedModeBanner: false,
home: LoginScreen(),
);
uj5u.com熱心網友回復:
如果您const為LoginScreen小部件創建建構式,這將解決MyApp問題。但是下一個問題來自var loginUsernameController = TextEditingController();我們現在已經創建的 const LoginScreen({Key? key}) : super(key: key);
對于const建構式類,它需要final類級別內的變數。
但TextEditingController()它本身是一個non-const建構式。
您還可以loginUsernameController在build方法內部初始化StatelessWidget并StatefulWidget使用initState。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398576.html
