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');
            });
          },
        )
      ],
    );
  }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章