Flutter StatelessWidget和StatefulWidget

发布于 3 年前 作者 phonegap100 486 次浏览 最后一次编辑是 3 年前 来自 分享

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

Flutter StatelessWidget是无状态组件,状态不可变的widget

Flutter StatefulWidget是有状态组件,持有的状态可能在widget生命周期改变。通俗的讲:如果我们想改变页面中的数据的话这个时候就需要用到StatefulWidget

StatelessWidget是无状态组件主要用于定义静态组件,比如前面讲的布局组件

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home:Scaffold(
        appBar: AppBar(
          title:Text("flutter demo")
        ),
        body:HomeContent() 
      )
    );
  }
}

class HomeContent extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
          child: Container(
              child: Text(
                '各位同学大家好我是主讲老师大地,各位同学大家好我是主讲老师大地',
                textAlign:TextAlign.left,
                overflow:TextOverflow.ellipsis ,
                // overflow:TextOverflow.fade ,
                maxLines: 2,
                textScaleFactor: 1.8,
                style:TextStyle(
                  fontSize: 16.0,
                  color:Colors.red,
                  // color:Color.fromARGB(a, r, g, b)
                  fontWeight: FontWeight.w800,
                  fontStyle: FontStyle.italic,
                  decoration:TextDecoration.lineThrough,
                  decorationColor:Colors.white,
                  decorationStyle: TextDecorationStyle.dashed,
                  letterSpacing: 5.0

                )
              
              ),
              height: 300.0,
              width: 300.0,
              decoration: BoxDecoration(
                color: Colors.yellow,
                border: Border.all(
                  color: Colors.blue,
                  width: 2.0
                ),
                borderRadius: BorderRadius.all(
                //  Radius.circular(150),    //圆形
                  Radius.circular(10),  
                )
              ),            
              alignment: Alignment.bottomLeft,
            


          ),
    );
  }
  
}

Flutter StatefulWidget是有状态组件主要用于定义动态组件

demo1:Flutter StatefulWidget实现点击按钮让计数器加1

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),      
        ElevatedButton(
          child: Text("按钮"),
          onPressed: (){
              // setState()   //错误写法       没法改变页面里面的数据
	            this.countNum++;
              print(this.countNum);
          },
        )
      ],
    );
  }
}



demo2:Flutter StatefulWidget实现点击按钮给list增加数据

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 StatefulWidget {
  //Flutter2.2.0之后需要注意把Key改为可空类型  {Key? key} 表示Key为可空类型
  HomePage({Key? key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  List 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),        
        ElevatedButton(
          child: Text("按钮"),
          onPressed: (){
            setState(() {
                this.list.add('新增数据1');
                this.list.add('新增数据2');
            });
          },
        )
      ],
    );
  }
}


回到顶部