Flutter 第二天:状态组件

37 阅读1分钟

image.png

无状态组件

继承 StatelessWidget 类,并重写其中的 build 方法,返回一个 Widget

快速创建:stless

代码

import 'package:flutter/material.dart';

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

class MainPage extends StatelessWidget {
  const MainPage({super.key});

  @override
  Widget build(final BuildContext context) {
    return MaterialApp(
      title: "Flutter 第二天",

      home: Scaffold(
        appBar: AppBar(title: Center(child: Text("顶部区域"))),
        body: Center(child: Text("中间区域")),
        bottomNavigationBar: SizedBox(
          height: 80,
          child: Center(child: Text("底部区域")),
        ),
      ),
    );
  }
}

有状态组件

两个类

  • 第一个类继承 StatefulWidget,实现 build 方法,对外暴露这个类

  • 第二个类继承 State<?>,中间泛型是第一个类,这个是私有的内部类,负责管理数据,处理业务逻辑和渲染视图

生命周期

image.png

快速创建:stful

代码

import 'package:flutter/material.dart';

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

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MainPageState();
  }
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(final BuildContext context) {
    return MaterialApp(
      title: "Flutter 第二天",
      home: Scaffold(
        appBar: AppBar(title: Center(child: Text("顶部区域"))),
        body: Center(child: Text("中间区域")),
        bottomNavigationBar: SizedBox(
          height: 80,
          child: Center(child: Text("底部区域")),
        ),
      ),
    );
  }
}