flutter学习六 flutter状态组件

Flutter 中自定义有状态组件
在 Flutter 中自定义组件其实就是一个类,这个类需要继承 StatelessWidget/StatefulWidget。
StatelessWidget 是无状态组件,状态不可变的 widget
StatefulWidget 是有状态组件,持有的状态可能在 widget 生命周期改变。通俗的讲:如果我
们想改变页面中的数据的话这个时候就需要用到 StatefulWidget

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Dart'),
        ),
        body: HomePage(),
      ),
    );
  }
}
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key:key);
  _HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
  List list = new List();
  @override
  Widget build(BuildContext context){
    return ListView(
      children: <Widget>[
        Column(children: this.list.map((value){
          return ListTile(
            title: Text("xxxs")
          );
        }).toList()),
        SizedBox(height: 20),
        RaisedButton(
          child: Text("button"),
          onPressed: (){
            setState(() {//通过这个方法来改变
              list.add('xxxxxxxx');
            });
          },
        )
      ],
    );
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_45561719/article/details/107881143
今日推荐