Flutter 13 - StatefulWidget 有状态组

2019-11-23  本文已影响0人  一叶知秋的码拉松

在 Flutter 中自定义组件其实就是一个类,这个类需要继承 StatelessWidget\StatefulWidget

通俗的讲:如果我们想改变页面中的数据的话这个时候就需要用到 StatefulWidget 。

使用 StatelessWidget 情况

class HomePage extends StatelessWidget {
  int countNum = 1; 
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 200),
        Text("${ this.countNum }"),
        SizedBox(height: 20),
        RaisedButton(
          child: Text("按钮"),
          onPressed: (){
            // setState()   // 错误写法 没法改变页面里面的数据
          this.countNum++;
              print(this.countNum);
          }
        )
      ]
    );
  }
}
HomPage.png

点击按钮是没法改变页面里的数据

使用 StatefullWidget 情况

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int countNum = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(height: 200),
        Chip(
          label:Text('${this.countNum}') ,
        ),
        SizedBox(height: 20),
        RaisedButton(
          child: Text('按钮'),
          onPressed: (){
             setState(() {   // 只有有状态组件里面才有
                  this.countNum++;
             });
          }
        )
      ]
    );
  }
}
上一篇 下一篇

猜你喜欢

热点阅读