Reputation: 49
I'm trying to get the value from the TextField then compare it to a string = '123'
If the value = '123' then alert 'Successful!' or else alert 'Failed!'
Here is my code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
class MyCustomForm extends StatefulWidget {
@override
_MyCustomFormState createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
TextEditingController myController = new TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if(myController == '123')
{
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Successful!'),
);
},
);
}
else
{
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text('Failed!'),
);
},
);
}
},
child: Icon(Icons.text_fields),
),
);
}
}
My code always shows failed even I entered '123'. Can someone help me to figure out what I did wrong here? Thank you
Upvotes: 0
Views: 99
Reputation: 456
To access the text inside a TextField Controller, you need to use myController.text, the myController is just a controller itself so you can't compare it to a String like that.
So, you should change this line
if(myController == '123')
into this
if(myController.text == '123')
Upvotes: 2