Flutter使用StatefulWidgets能够生成有状态对象的控件,然后用来保持状态
import 'package:flutter/material.dart';
void main(){
runApp(new MaterialApp(
title: "flutter控件状态改变",
home: new Counter(),
));
}
class Counter extends StatefulWidget{
@override
_CounterState createState()=>new _CounterState();
}
class _CounterState extends State<Counter>{
int _count = 0;
void _increamnet(){
setState(() {
_count+=1;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(
title: new Text("flutter控件改变"),
),
body: new Center(
child: new Text("$_count"),
),
floatingActionButton: new FloatingActionButton(onPressed: _increamnet,tooltip: "增加",child: new Icon(Icons.add),),
);
}
}
为什么StatefukWidget和State是单独的对象?
在flutter中,这两种类型的对象有不同的生命周期,控件是临时兑现个,用于构建应用程序的呈现。State对象在被build调用是是持久的,允许他们记住信息。