- 在flutter中自定义一个组件其实就是一个类。这个类需要继承StatelessWidget/StatefulWidget.
- StatefulWidget组件 有状态组件。持有的状态可能再widget生命周期改变。如果我们想改变页面中的数据的话就需要是用有状态的组件
我们使用Widgets构建UI,这些widgets有两种类型,stateful和stateless,由于整个APP全部使用widget构建,所以在构建每个widget时,都需要判断使用哪种状态,这就要求必须对状态有深入了解,才能确保每个决定都是准确无误的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import 'package:flutter/material.dart'; import './data/listData.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("有状态组件"), ), body: HomePage(), ), ); } }
class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key);
@override _HomePageState createState() => _HomePageState(); }
class _HomePageState extends State<HomePage> { int countNum = 0; @override Widget build(BuildContext context) { return Column( children: <Widget>[ SizedBox( height: 200.0, ), Text("nihao${this.countNum}"), SizedBox( height: 20.0, ), RaisedButton( onPressed: () { setState(() { this.countNum++; }); print(this.countNum); }, child: Text("buttom"), ), ], ); } }
|