【发布时间】:2021-03-13 12:38:11
【问题描述】:
我想更改登录/注册并创建新帐户/我已经有一个帐户文本,因此创建了 islogin boolean 但在 textbutton 屏幕中执行 setstate 后没有更新这里的问题。???我的代码___
import 'package:flutter/material.dart';
class AuthForm extends StatefulWidget {
@override
_AuthFormState createState() => _AuthFormState();
}
class _AuthFormState extends State<AuthForm> {
@override
Widget build(BuildContext context) {
final _formKey = GlobalKey<FormState>();
var isLogIn = true;
var _userEmail = '';
var _userPass = '';
var _userUsername = '';
//
void _trySubmit() {
final isValid = _formKey.currentState.validate();
FocusScope.of(context).unfocus();
if (isValid) {
_formKey.currentState.save();
print(_userEmail);
print(_userPass);
print(_userUsername);
}
}
return Center(
child: Card(
elevation: 20,
margin: EdgeInsets.all(20),
child: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(labelText: "Email"),
validator: (value) {
if (value.isEmpty || !value.contains("@")) {
return "Please Enter a Valid Email";
}
return null;
},
onSaved: (value) {
_userEmail = value;
},
),
if (!isLogIn)
TextFormField(
keyboardType: TextInputType.name,
decoration: InputDecoration(labelText: "User Name"),
validator: (value) {
if (value.isEmpty || value.length < 4) {
return "Please Enter Atleast 4 Charecter";
}
return null;
},
onSaved: (value) {
_userUsername = value;
},
),
TextFormField(
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(labelText: "Password"),
obscureText: true,
validator: (value) {
if (value.isEmpty || value.length < 7) {
return "Please Enter Atleast 7 Charecter";
}
return null;
},
onSaved: (value) {
_userPass = value;
},
),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: _trySubmit,
child: Padding(
padding: const EdgeInsets.all(4),
child: Text(
isLogIn ? "Log In" : "Sign Up",
style: TextStyle(fontSize: 25),
),
),
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
),
),
TextButton(
onPressed: () {
setState(() {
isLogIn = !isLogIn;
print(isLogIn);
});
},
child: Text(isLogIn
? "Create New Account"
: "I Already have a Account"),
),
],
)),
),
),
);
}
}
【问题讨论】:
-
将变量放在 Widget build(BuildContext context) 函数之外