我正在尝试将文本与文本字段进行比较,如果我的第一个键盘击键与文本的第一个元素匹配,我想增加分数,但是下面的代码不起作用,为什么它不起作用?
var textField = TextField(
controller: myController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide(color: Colors.black))),
autocorrect: false,
textAlign: TextAlign.center,
onChanged: (text) {
for (int x = 0; x < text.length; x++) {
if (myController.text[x] == textP1[x]) {//textP1 is my original text
score++;
if (score == textP1.length) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text("YOU WON !!!!"),
);
},
);
}
}
}
});
答案 0 :(得分:1)
也许您需要在循环开始之前重设分数。
class SampleState extends StatefulWidget {
@override
_SampleStateState createState() => _SampleStateState();
}
class _SampleStateState extends State<SampleState> {
final textP1 = "suman";
var myController = TextEditingController();
var score = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
centerTitle: true,
title: new Text('Sign in',
style: TextStyle(fontWeight: FontWeight.bold))),
body: new Container(
child: Column(
children: <Widget>[
new TextField(
controller: myController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(50),
borderSide: BorderSide(color: Colors.black))),
autocorrect: false,
textAlign: TextAlign.center,
onChanged: (text) {
score = 0;
for (int x = 0; x < text.length; x++) {
if (myController.text[x] == textP1[x]) {
//textP1 is my original text
setState(() {
score++;
});
print(score);
if (score == textP1.length) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text("YOU WON !!!!"),
);
},
);
}
}
}
}),
Text("Score: $score")
],
)));
}
}