首页 > 其他分享 >前端学习-flutter学习-004-状态管理

前端学习-flutter学习-004-状态管理

时间:2024-07-07 23:08:43浏览次数:14  
标签:Widget 004 学习 Colors extends key child active flutter

《Flutter实战·第二版》

  • Widget管理自身状态:自己继承StatefulWidget,自己内部设置变量(State)并进行管理
  • 父Widget管理子Widget的状态:parent继承自StatefulWidget,设置变量及函数,传递给child;child继承自StatelessWidget
  • 混合状态管理:既接受来自parent的变量和函数,自己继承自StatefulWidget,内部也管理参数(状态)
  • 全局状态管理:需要一些跨组件(包括跨路由)的状态需要同步时(如设置应用的语言)
import 'package:flutter/material.dart';
import 'dart:ui';
  // import 'package:flutter/cupertino.dart';
  // void main() {
  //   runApp(const MyApp());
  // }
  
  void main() => runApp(const MyApp());
  // void main() => runApp(CupertinoApp(home: CupertinoTestRoute()));

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home:  HomePage(),
    );
  }
}


class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text("Widget管理自身状态"),
          backgroundColor: Colors.green,
      ),
      body: Center(
        child: Column(
          children: [
            TapboxA(),
            ParentWidget(),
            ParentWidgetC(),
          ],
        ),
      ),
    );
    // return CounterWidget();
  }
}

// TapboxA 管理自身状态.
//------------------------- TapboxA ----------------------------------

class TapboxA extends StatefulWidget {
  TapboxA({Key? key}) : super(key: key);

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

class _TapboxAState extends State<TapboxA> {
  bool _active = false;

  void _handleTap() {
    setState(() {
      _active = !_active;
    });
  }

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: Center(
        child: Container(
          child: Center(
            child: Text(
              _active ? 'Widget管理自身状态Active' : 'Widget管理自身状态Inactive',
              style: TextStyle(fontSize: 32.0, color: Colors.white),
            ),
          ),
          width: 200.0,
          height: 200.0,
          decoration: BoxDecoration(
            color: _active ? Colors.lightGreen[700] : Colors.grey[600],
          ),
        ),
      ),
    );
  }
}

// ParentWidget 为 TapboxB 管理状态.
//------------------------ ParentWidget --------------------------------

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  bool _active = false;

  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TapboxB(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}

//------------------------- TapboxB ----------------------------------

class TapboxB extends StatelessWidget {
  TapboxB({Key? key, this.active = false, required this.onChanged})
      : super(key: key);

  final bool active;
  final ValueChanged<bool> onChanged;

  void _handleTap() {
    onChanged(!active);
  }

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: Container(
        child: Center(
          child: Text(
            active ? '父Widget管理子Widget的状态Active' : '父Widget管理子Widget的状态Inactive',
            style: TextStyle(fontSize: 32.0, color: Colors.white),
          ),
        ),
        width: 200.0,
        height: 200.0,
        decoration: BoxDecoration(
          color: active ? Colors.lightGreen[700] : Colors.grey[600],
        ),
      ),
    );
  }
}


// 混合状态管理
//---------------------------- ParentWidget ----------------------------

class ParentWidgetC extends StatefulWidget {
  @override
  _ParentWidgetCState createState() => _ParentWidgetCState();
}

class _ParentWidgetCState extends State<ParentWidgetC> {
  bool _active = false;

  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: TapboxC(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}

//----------------------------- TapboxC ------------------------------

class TapboxC extends StatefulWidget {
  TapboxC({Key? key, this.active = false, required this.onChanged})
      : super(key: key);

  final bool active;
  final ValueChanged<bool> onChanged;

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

class _TapboxCState extends State<TapboxC> {
  bool _highlight = false;

  void _handleTapDown(TapDownDetails details) {
    setState(() {
      _highlight = true;
    });
  }

  void _handleTapUp(TapUpDetails details) {
    setState(() {
      _highlight = false;
    });
  }

  void _handleTapCancel() {
    setState(() {
      _highlight = false;
    });
  }

  void _handleTap() {
    widget.onChanged(!widget.active);
  }

  @override
  Widget build(BuildContext context) {
    // 在按下时添加绿色边框,当抬起时,取消高亮
    return GestureDetector(
      onTapDown: _handleTapDown, // 处理按下事件
      onTapUp: _handleTapUp, // 处理抬起事件
      onTap: _handleTap,
      onTapCancel: _handleTapCancel,
      child: Container(
        child: Center(
          child: Text(
            widget.active ? '混合状态管理Active' : '混合状态管理Inactive',
            style: TextStyle(fontSize: 32.0, color: Colors.white),
          ),
        ),
        width: 200.0,
        height: 200.0,
        decoration: BoxDecoration(
          color: widget.active ? Colors.lightGreen[700] : Colors.grey[600],
          border: _highlight
              ? Border.all(
            color: Colors.teal,
            width: 10.0,
          )
              : null,
        ),
      ),
    );
  }
}

标签:Widget,004,学习,Colors,extends,key,child,active,flutter
From: https://www.cnblogs.com/ayubene/p/18288612

相关文章

  • DataWhale夏令营(机器学习方向)——分子性质AI预测挑战赛
     #AI夏令营#Datawhale#夏令营该笔记是在博主Mr.chenlex跑分后的基础上加以改进,原文连接:DatawhaleAI夏令营-机器学习:分子性质AI预测挑战赛#ai夏令营datawhale#夏令营-CSDN博客Baseline改进前后代码介绍Baseline改进前后跑分结果直接套用原博主的Baseline(需另进行库的......
  • 强化学习与控制模型结合例子
    强化学习与模型控制结合强化学习(ReinforcementLearning,RL)与控制模型结合,可以通过整合传统控制理论和现代RL算法,利用控制模型提供的动态信息和稳定性保障,同时利用RL的学习能力优化控制策略。这种结合的方式被称为模型辅助强化学习(Model-AssistedReinforcementLearning)......
  • 【机器学习】基于线性回归的医疗费用预测模型
    文章目录一、线性回归定义和工作原理假设表示二、导入库和数据集矩阵表示可视化三、成本函数向量的内积四、正态方程五、探索性数据分析描述性统计检查缺失值数据分布图相关性热图保险费用分布保险费用与性别和吸烟情况的关系保险费用与子女数量的关系保险费用与地区......
  • HarmonyOS NEXT 学习笔记2 --百度小练习
    1.百度的小案例:@Entry@ComponentstructPage0707_baidu{@Statemessage:string='HelloWorld';build(){Column({space:20}){Image('https://www.baidu.com/img/flexible/logo/pc/result.png').width('50%'......
  • [C语言学习]--数据类型和变量
    文章目录前言一、数据类型介绍1.内置类型1.1.整型1.2.浮点型1.3.字符型1.4.布尔类型2.自定义类型 3.数据类型的长度4.sizeof操作符 5.signed和unsigned二、变量1.变量的创建2.变量的分类3.算术操作符(运算符)3.1.+和-3.2. *3.3./ 3.4% 4.赋......
  • 强化学习-表格型算法Q学习稳定倒立摆小车
    [[Q学习]]是表格型算法的一种,主要维护了一个Q-table,里面是状态-动作对的价值,分别由一个状态和一个动作来索引。这里以一个经典的道理摆小车问题来说明如何使用[[Q学习]]算法。这里会用到两个类,agent和brain。brain类中来维护[[强化学习的基本概念|强化学习]]算法的......
  • 学习Linux LVM,这篇文章就够了
      (1)引言     LVM(LogicalVolumeManager)逻辑卷管理,是在硬盘分区和文件系统之间添加的一个逻辑层,为文件系统屏蔽下层硬盘分区布局,并提供一个抽象的盘卷,在盘卷上建立文件系统。管理员利用LVM可以在硬盘不用重新分区的情况下动态调整文件系统的大小,并且利用LVM管理的......
  • 昇思25天学习打卡营第11天 | LLM原理和实践:基于MindSpore实现BERT对话情绪识别
    1.基于MindSpore实现BERT对话情绪识别1.1环境配置#实验环境已经预装了mindspore==2.2.14,如需更换mindspore版本,可更改下面mindspore的版本号!pipuninstallmindspore-y!pipinstall-ihttps://pypi.mirrors.ustc.edu.cn/simplemindspore==2.2.14#该案例在min......
  • 昇思25天学习打卡营第10天 | 自然语言处理:RNN实现情感分类
    1.RNN实现情感分类1.2概述情感分类是自然语言处理中的经典任务,是典型的分类问题。本节使用MindSpore实现一个基于RNN网络的情感分类模型,实现如下的效果:输入:Thisfilmisterrible正确标签:Negative(负面)预测标签:Negative输入:Thisfilmisgreat正确标签:......
  • Kaggle网站免费算力使用,深度学习模型训练
    声明:本文主要内容为:kaggle网站数据集上传,训练模型下载、模型部署、提交后台运行等教程。1、账号注册此步骤本文略过,如有需要可以参考其他文章。2、上传资源不论是上传训练好的模型进行预测,还是训练用的数据集都可以按此步骤上传。如果是数据集的话,先要将数据集进行压缩,才......