StatefulWidget和StatelessWidget

2021-05-13  本文已影响0人  稀释1

StatefulWidget 有状态组件

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

StatelessWidget中实现数据变化
在使用StatefulWidget前,先看一下在StatelessWidget中,点击按钮,改变数据后的效果

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo')
        ),
        body: HomePage(),
      )
    );
  }
}

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: (){
              this.countNum++;
            print(this.countNum);
          },
        )
      ],
    );
  }
}
image.png

此时,当点击按钮,改变countNum的值时,发现控制台里面的打印中,数值是变化的,但是页面中却没有变化效果,此时就需要使用StatefulWidget了

StatefulWidget中改变数据

StatefulWidget是一个抽象类,在这个类中,有一个抽象方法createState(),然后在这个抽象方法中调用自定义的_HomePageState()类,_HomePageState()类需要继承State类,最后在这个类中实现build()方法。

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++;
             });
          },
        )
      ],
    );
  }
}
image.png

添加数据

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(value),
            );
          }).toList()
        ),
        SizedBox(height: 20),
        RaisedButton(
          child: Text("按钮"),
          onPressed: (){
            setState(() {
                this.list.add('新增数据1');
                this.list.add('新增数据2');
            });
          },
        )
      ],
    );
  }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读