我想做报警对话框数量增加(+1)数量减少(-1)数值重置(R),但它没有出现在屏幕上,当我保存文件的值出现在屏幕上,我该怎么做?İmage:enter image description here
wlwcrazw1#
您没有使用StateFull Widget和setState()。当你想动态改变屏幕上的值时,调用setState()检查以下示例:
StateFull Widget
setState()
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } int currentValue = 0; class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primaryColor: Colors.indigo, useMaterial3: true, ), home: const MyHomePage(), ); } } //use stateful widget when you want to change state class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ //show the current value on screen Text( '$currentValue', textAlign: TextAlign.center, ), //button to show dialog ElevatedButton( child: Text("show Dialog "), onPressed: () { showDialog( context: context, builder: (BuildContext context) { return Dialog(); }); }, ), ], ), ); } } class Dialog extends StatefulWidget { const Dialog({super.key}); @override State<Dialog> createState() => _DialogState(); } class _DialogState extends State<Dialog> { @override Widget build(BuildContext context) { return AlertDialog( title: Text('$currentValue'), actions: [ //button to increase the value of currentValue ElevatedButton( onPressed: () { //call setState, it will Update the state setState(() { //increment the value currentValue++; }); }, child: Text('Increase')), ElevatedButton( onPressed: () { setState(() { //reduce the value currentValue--; }); }, child: Text('Decrease')), ElevatedButton( onPressed: () { setState(() { //reduce the value currentValue = 0; }); }, child: Text('Reset')), ElevatedButton( onPressed: () { Navigator.pop(context); }, child: Text('Remove Dialog')), ], ); } }
unhi4e5o2#
请将类StatelessWidget设置为StatefullWidget,并在调用onPressed()时使用setState
StatelessWidget
StatefullWidget
onPressed()
setState
onPressed: () { setState(() { //logic }); }
希望这有帮助!
2条答案
按热度按时间wlwcrazw1#
您没有使用
StateFull Widget
和setState()
。当你想动态改变屏幕上的值时,调用
setState()
检查以下示例:
unhi4e5o2#
请将类
StatelessWidget
设置为StatefullWidget
,并在调用onPressed()
时使用setState
希望这有帮助!