StatefulWidget 有狀態組件


在 Flutter 中自定義組件其實就是一個類,這個類需要繼承 StatelessWidget/StatefulWidget:
  • StatelessWidget 是無狀態組件,狀態不可變的 widget
  • StatefulWidget 是有狀態組件,持有的狀態可能在 widget 生命周期改變。通俗的講:如果我們想改變頁面中的數據的話這個時候就需要用到 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);
          },
        )
      ],
    );
  }
}

  

 此時,當點擊按鈕,改變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++;
             });
          },
        )
      ],
    );
  }
}

 

添加數據

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

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM