Flutter有状态组件

简介

  • StatefulWidget:有状态组件,持有的状态可以在Widget声明周期改变(即数据可以进行修改)

class HomeContent extends StatefulWidget {
  HomeContent({Key key}) : super(key: key);
  _HomeContentState createState() => _HomeContentState();
}


class _HomeContentState extends State<HomeContent> {
  int countNum = 0;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        SizedBox(height: 200),
        Chip(
          label: Text('${this.countNum}'),
        ),
        SizedBox(height: 20),
        RaisedButton(
          child: Text("click"),
          onPressed: () {
            setState(() {
              countNum++;
            });
          },
        )
      ],
    );
  }
}
eg:动态增加列表
class HomeContent extends StatefulWidget {
  HomeContent({Key key}) : super(key: key);
  _HomeContentState createState() => _HomeContentState();
}


class _HomeContentState extends State<HomeContent> {
  List list=new List();
  @override
  Widget build(BuildContext context) {
    return ListView(


      children: <Widget>[
        Column(
            children: this.list.map((value){
              return ListTile(
                title: Text(value),
              );
            }).toList()
        ),
        SizedBox(height: 20),
        RaisedButton(
          child: Text("按钮"),
          onPressed: (){
            setState(() {
              this.list.add('新增数据1');
              this.list.add('新增数据2');
            });
          },
        )
      ],
    );
  }
}

在这里插入图片描述

发布了175 篇原创文章 · 获赞 56 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39424143/article/details/104752907