Reputation: 491
I'm trying to implement "forgot password" functionality in my web app.
I have a email text editing controller as the input field and an elevated button which will eventually push the value to my forgotpassword function.
To handle errors, i'm trying to implement an if statement to ensure that if the textfield is empty, the request isn't sent.
When testing the block however, Flutter seems to think there is a value in the textfield without me actually entering anything? Can someone explain where i'm going wrong? Thanks. Here's my code:
class ForgotPasswordScreen extends StatelessWidget {
final TextEditingController forgotPasswordController =
TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Forgot Password'),
),
body: Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.5,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: forgotPasswordController,
decoration: InputDecoration(
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder()),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
try {
if (forgotPasswordController.value != null) {
print('Success');
} else {
print("fail");
}
} catch (e) {
print(e);
}
},
child: Text('Send reset link')),
)
],
),
),
));
}
}
Upvotes: 4
Views: 15426
Reputation: 5746
By default value of TextEditingController
is empty, not the null
.
.value
isn't String. It's TextEditingValue
's instance, which isn't null. That's why it goes to else
. Use .isEmpty
on .text
since it returns String.
if (forgotPasswordController.text.isNotEmpty) {
// pass
} else {
// fail
}
Upvotes: 16