【发布时间】:2021-11-23 10:53:15
【问题描述】:
我是 Flutter 的新手。我正在尝试使用按钮构建一个基本的骰子应用程序。单击按钮时,显示的文本会更新为随机数。
import 'package:flutter/material.dart';
import 'dart:math';
int dice = 0;
void main() {
int dice = 0;
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
title: const Text('Quick Dice'),
backgroundColor: Colors.blueGrey,
),
body: Center(
child: MaterialButton(
onPressed: () {
rollDice();
},
child: new Text('$dice'),
),
),
),
),
);
}
void rollDice(){
dice = Random().nextInt(6) + 1;
print('In Roll Dice()');
print('$dice');
}
单击按钮时,我可以看到正在调用函数 rollDice() 并且正在更新 $dice 的值,但在屏幕上,该值永远不会更新。
我有什么遗漏吗?是否应该以某种方式刷新子文本元素以在按钮按下时显示新值?
【问题讨论】:
-
你应该在 rollDice() 方法中使用 setState()。