在Flutter中自定义组件其实就是一个类,这个类需要继承StatelessWidget/StatefulWidget。 StatelessWidget是无状态组件,状态不可变的widget StatefulWidget是有状态组件,持有的状态可能在widget生命周期改变。 通俗的讲:如果我们想改变页面中的数据的话这个时候就需要用到StatefulWidget
StatefulWidget实现一个计数器的功能
//StatefulWidget有状态的组件 class HomePage1 extends StatefulWidget { HomePage1({super.key}); @override State<HomePage1> createState() => _nameState(); } class _nameState extends State<HomePage1> { int _countNum = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("这是导航栏")), body: Center(child: Column( mainAxisAlignment:MainAxisAlignment.center, children: [ Text("${_countNum}",style: Theme.of(context).textTheme.headline1,), ElevatedButton(onPressed: () { setState(() { //改变值 并且重新执行 _countNum ++; }); print("打印${_countNum}"); }, child: const Text("增加",style: TextStyle(fontSize: 10),),) ],)), ); } }
StatefulWidget实现一个动态列表
//StatefulWidget有状态的组件 class HomePage2 extends StatefulWidget { const HomePage2({super.key}); @override State<HomePage2> createState() => _HomePage2State(); } class _HomePage2State extends State<HomePage2> { List<String> _list = []; int _number = 0; //定义数组 @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("这是导航栏")), floatingActionButton: FloatingActionButton( onPressed: () { //改变数据必须加上 setState(() { _number++; this._list.add("我是一个列表$_number"); }); }, child: const Icon(Icons.add), ), body: ListView( children: _list.map((v) { return ListTile( title: Text(v), ); }).toList()), ); } }
标签:StatefulWidget,const,Text,State,StatelessWidget,extends,override,Flutter From: https://www.cnblogs.com/xbinbin/p/17850064.html