我在下面創建了一個函式
nextQuestion() {
setState(() {
questionIndex ;
});
print('pressed');
}
然后我創建了下面的類,并在上面的方法中傳遞了一個 onPressed 屬性的建構式
class Answer extends StatelessWidget {
final String answer;
final VoidCallback? selectHandler;
// ignore: use_key_in_widget_constructors
const Answer({required this.answer, this.selectHandler});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: selectHandler,
child: SizedBox(
width: double.infinity,
child: Center(
child: Text(
answer,
),
),
),
);
}
}
然后我使用類的建構式并傳入函式來更新我螢屏上的文本,該文本位于以questionIndex作為索引的串列中
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Question(question: questions[questionIndex]),
Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
Answer(selectHandler: nextQuestion(), answer: 'Yellow'),
],
),
這不起作用/按下按鈕后不更新螢屏上的文本
uj5u.com熱心網友回復:
我重新創建了代碼,它對我有用,但有一些例外:
- Answer(selectHandler: nextQuestion(), answer: 'Yellow'),錯了。你必須使用selectHandler:nextQuestion(函式后沒有())
- 在另一個有狀態小部件中使用答案小部件。
如果你做了所有這些但它仍然不起作用運行 flutter clean 然后 flutter pub get (首先關閉除錯會話)
如果這不起作用,則問題出在您的問題小部件上。你能分享一下代碼嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/392807.html
上一篇:如何將行對齊到固定位置
