我是 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 的值,但在螢屏上,該值永遠不會更新。
有什么我想念的嗎?是否應該以某種方式重繪 子文本元素以在按鈕按下時顯示新值?
uj5u.com熱心網友回復:
這樣做( StatefulWidget ):
void main(){
runApp(MaterialApp(
home: UpdateScreen(),
));
}
class UpdateScreen extends StatefulWidget{
@override
UpdateScreenState createState() => UpdateScreenState();
}
class UpdateScreenState extends State<UpdateScreen>{
int dice = 0;
@override
Widget build(BuildContext context) {
return 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(){
setState(() {
dice = Random().nextInt(6) 1;
print('In Roll Dice()');
print('$dice');
});
}
}
uj5u.com熱心網友回復:
試試下面的代碼希望它對你有幫助。
|
uj5u.com熱心網友回復:
您的方法正在運行 find 但值未在 UI 中更新,因為您沒有在應用程式的任何地方使用 Set State。只需為您的應用程式主體創建一個單獨的有狀態小部件,并在 onPressed 中呼叫 setState 方法來更新您的 UI。
uj5u.com熱心網友回復:
要更新螢屏上的資料,您必須使用狀態管理,如 provider、Getx、block 等。或者您可以在 rollDice() 函式中使用 setState 方法,然后小部件將重建并更新您的資料。像這樣的——
void rollDice(){
setState(() {
dice = Random().nextInt(6) 1
});
print('In Roll Dice()');
print('$dice');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364072.html
