Flutter中StatefulWidget和StatelessWidget的理解

原创
2020/10/23 22:48
阅读数 202

刚开始学Flutter的时候,通过文档可以了解到StatelessWidget是无状态的组件,而StatefulWidget是有状态的组件,所以遇到「需要改变状态」的场景,就应该使用StatefulWidget。但是哪些是有状态的场景呢?

我们做个测试

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_app/my_state_less.dart';
import 'package:flutter_app/my_statefull.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(onPressed: (){
              setState(() {});
            }, child: Text("刷新")),
            MyStateLess(),
            MyStateful()
          ],
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

MyStateLess:

import 'package:flutter/cupertino.dart';

class MyStateLess extends StatelessWidget{

  MyStateLess();

  @override
  Widget build(BuildContext context) => Text("内容");

}

MyStateful:

import 'package:flutter/cupertino.dart';

class MyStateful extends StatefulWidget{

  MyStateful();

  @override
  State<StatefulWidget> createState() => _MyStateFulState();

}

class _MyStateFulState extends State<MyStateful>{

  _MyStateFulState();

  @override
  Widget build(BuildContext context) => Text("状态");

}

在主页中添加一个StatelessWidget和一个StatefulWidget,通过点击按钮触发setState

第一次打开的流程

  1. StatelessWidget的构造方法
  2. StatefulWidget的构造方法
  3. _MyHomePageState的build方法
  4. StatelessWidget的build方法
  5. StatefulWidget的createState方法
  6. _MyStateFulState的构造方法
  7. _MyStateFulState的build方法

setState之后的流程

  1. StatelessWidget的构造方法
  2. StatefulWidget的构造方法
  3. _MyHomePageState的build方法
  4. StatelessWidget的build方法
  5. _MyStateFulState的build方法

总结

我们发现setState后,StatefulWidget不会重新创建State了,所以所谓StatefulWidget其实应该理解为可以保存状态的组件

展开阅读全文
打赏
0
0 收藏
分享
加载中
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部