【发布时间】:2020-12-23 05:51:59
【问题描述】:
假设以下简单的StatefulWidget 示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
int value = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('App Example')),
body: Row(children:[
Text("hello"),
RaisedButton(
textColor: Colors.white,
color: Colors.blue,
onPressed: (){setState(() { value+=1; });},
child: new Text("Add"),
)
]),
),
);
}
}
我的主要问题是:每次value 更改时如何重绘Text("hello")?我以Text 为例,但它可能是一个具有内部状态的小部件,我想在值更改时重新绘制它。它不一定取决于value,但我想在value 更改时重绘。
【问题讨论】:
-
但是你写的都是写的,你可以测试一下,比如设置Text("hello $value"),状态会更新,因为你在onPressed方法中使用了setState。