我正在努力用 flutter 构建一个问答游戏。我是颤振的新手。在这里为一个问题创建四个
buttons
。当按下应答按钮时,它会运行 checkAnswer
方法,之后我想将 backgroundColor
更改为 buttons
。当我从 onPressed: result == null
删除 button onPressed
时,它会更改按钮的 backgroundColor
。但用户可以在单击一次后再次单击按钮。因此,当我添加 onPressed: result == null
来防止它时,就不再更新按钮的 backgroundColor
了。我不明白这里有什么问题。这看起来是一个愚蠢的问题。
...(currentQuestion["options"] as List<String>)
.map((option) =>
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
// Alttan boşluk
child: ElevatedButton(
onPressed: result == null
? () {
setState(() {
selectedOption = option;
});
checkAnswer(option);
}
: null,
style: ElevatedButton.styleFrom(
backgroundColor: result ==
AppLocalizations.of(context)
?.truth_answer &&
selectedOption == option
? Colors.red
: result ==
AppLocalizations.of(context)
?.wrong_answer &&
selectedOption == option
? Colors.blue
: result ==
AppLocalizations.of(context)
?.wrong_answer &&
currentQuestion["answer"]
as String ==
option
? Colors.red
: Colors.blue),
child: Text(
option,
style: const TextStyle(color: Colors.black87),
),
))),
void checkAnswer(String answer) {
if (timer != null) {
timer!.cancel();
}
setState(() {
if (answer == questions[currentQuestionIndex]["answer"] as String) {
result = AppLocalizations.of(context)?.truth_answer;
} else {
result = AppLocalizations.of(context)?.wrong_answer;
}
print("Seçilen seçenek: $selectedOption");
print("Doğru cevap: ${questions[currentQuestionIndex]["answer"]}");
print("Sonuç: $result");
});
}
在 stackoverflow 搜索了很多问题后,我得到了解决方案。我更改了这些部分的代码:
ElevatedButton.styleFrom(
backgroundColor: result ==
AppLocalizations.of(context)
?.truth_answer &&
selectedOption == option
? Colors.red
: result ==
AppLocalizations.of(context)
?.wrong_answer &&
selectedOption == option
? Colors.blue
: result ==
AppLocalizations.of(context)
?.wrong_answer &&
currentQuestion["answer"]
as String ==
option
? Colors.red
: Colors.blue),
使用这些代码:
ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith<Color>((states) {
if (result == AppLocalizations.of(context)?.truth_answer && selectedOption == option) {
return Colors.green;
} else if (result == AppLocalizations.of(context)?.wrong_answer && selectedOption == option) {
return Colors.blue;
} else if (result == AppLocalizations.of(context)?.wrong_answer && currentQuestion["answer"] as String == option) {
return Colors.green;
} else {
return Colors.blue.shade200;
}
}),
),