为什么选择正确答案时返回false?我有问题和答案。问题和答案是随机的。有一个问题和四个答案。当我选择corrrect answer时,它返回false。为什么会这样?我正在试着解决这个问题。我不明白为什么会这样。如何解决这个问题?
var characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',];
final random = Random();
var randomElement = characters[random.nextInt(characters.length)];
var randomElement2 = characters[random.nextInt(characters.length)];
var randomElement3 = characters[random.nextInt(characters.length)];
var randomElement4 = characters[random.nextInt(characters.length)];
var answers = [randomElement, randomElement2, randomElement3, randomElement4];
class MyHomePage extends StatefulWidget {
MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selectedIndex = -1;
@override
Widget build(BuildContext context) {
return SafeArea(
child: SingleChildScrollView(
physics: ScrollPhysics(),
child: Column(
children: [
Text(
'Select: $randomElement',
style: TextStyle(fontSize: 22),
),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: answers.length,
itemBuilder: (BuildContext context, int index) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor:
selectedIndex == index ? Colors.grey : Colors.white,
),
onPressed: () {
setState(() {
selectedIndex = index;
});
},
child: Text(
answers[index],
),
);
}),
ElevatedButton(
onPressed: () {
setState(() {
randomElement = characters[random.nextInt(characters.length)];
});
randomElement2 = characters[random.nextInt(characters.length)];
randomElement3 = characters[random.nextInt(characters.length)];
randomElement4 = characters[random.nextInt(characters.length)];
setState(() {
answers = [
randomElement,
randomElement2,
randomElement3,
randomElement4
];
});
answers.shuffle();
if (randomElement == answers[selectedIndex]) {
debugPrint('correct');
} else {
debugPrint('false');
}
selectedIndex = -1;
},
child: Text('Next'),
)
],
),
),
);
}
}
1条答案
按热度按时间mm9b1k5b1#
主要问题是首先生成一个新的答案批,其中变量
randomElement
也获得一个新的随机值。然后检查新的随机值是否与用户选择的旧值相同。要解决这个问题,您应该移动逻辑以检查用户是否正确选择。只有在加载了新问题并且旧问题的检查部分已经完成时,才应该生成新的随机集。