Flutter组件 StatefulWidget、StatelessWidget 可继承写法

前言

学过Java的同学,应该都知道面向对象语言的三大特征,封装、继承、多态;

Dart也是面向对象的语言,但是在Flutter中的很多组件都被下划线 '_' 标记为私有,导致无法继承,本文将介绍一种非私有的创建组件写法。

当前案例 Flutter SDK版本:3.13.2

效果图

StatefulWidget

基类:base_stateful_widget.dart

import 'package:flutter/material.dart';class BaseStatefulWidget extends StatefulWidget {final Map<String,dynamic>? arguments;const BaseStatefulWidget({super.key,this.arguments});@overrideState<BaseStatefulWidget> createState() => BaseStatefulWidgetState();
}class BaseStatefulWidgetState<T extends StatefulWidget> extends State<BaseStatefulWidget> {@overrideWidget build(BuildContext context) {return const Placeholder();}}

创建第一个非私有的StatefulWidget组件:parent_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/base/base_stateful_widget.dart';class ParentBox extends BaseStatefulWidget {const ParentBox({super.key,super.arguments});@overrideParentBoxState<ParentBox> createState() => ParentBoxState();
}class ParentBoxState<T extends ParentBox> extends BaseStatefulWidgetState<ParentBox> {@overrideWidget build(BuildContext context) {final size = double.parse((widget.arguments?['size'] ?? 50).toString());return Container(width: size,height: size,margin: const EdgeInsets.only(bottom: 12),color: Colors.green,alignment: Alignment.center,child: content(),);}content() {final content = widget.arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.yellow,));}}

子类:child_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/widget/parent_box.dart';class ChildBox extends ParentBox {const ChildBox({super.key,super.arguments});@overrideChildBoxState<ChildBox> createState() => ChildBoxState();
}class ChildBoxState<T extends ChildBox> extends ParentBoxState<ChildBox> {@overridecontent() {final content = widget.arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.white,));}}

子孙类:posterity_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/widget/child_box.dart';class PosterityBox extends ChildBox {const PosterityBox({super.key,super.arguments});@overrideChildBoxState<ChildBox> createState() => PosterityBoxState();
}class PosterityBoxState<T extends PosterityBox> extends ChildBoxState<PosterityBox> {@overridecontent() {final content = widget.arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.black,));}}

StatelessWidget

基类:base_stateless_widget.dart

import 'package:flutter/material.dart';class BaseStatelessWidget extends StatelessWidget {final Map<String,dynamic>? arguments;const BaseStatelessWidget({super.key, this.arguments});@overrideWidget build(BuildContext context) {return const Placeholder();}
}

创建第一个非私有的StatelessWidget组件:school_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/base/base_stateless_widget.dart';class SchoolBox extends BaseStatelessWidget {const SchoolBox({super.key,super.arguments});@overrideWidget build(BuildContext context) {final size = double.parse((arguments?['size'] ?? 50).toString());return Container(width: size,height: size,margin: const EdgeInsets.only(bottom: 12),color: Colors.cyan,alignment: Alignment.center,child: content(),);}content() {final content = arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.white,));}}

子类:teacher_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/widget/school_box.dart';class TeacherBox extends SchoolBox {const TeacherBox({super.key,super.arguments});@overridecontent() {final content = arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.yellow,));}}

子孙类:student_box.dart

import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/widget/teacher_box.dart';class StudentBox extends TeacherBox {const StudentBox({super.key,super.arguments});@overridecontent() {final content = arguments?['content'];return Text(content,style: const TextStyle(fontSize: 20,color: Colors.greenAccent,));}}

入口相关文件:test_stateful_widget.dart、test_stateless_widget.dart、main.dart

import 'package:flutter/material.dart';import '../widget/child_box.dart';
import '../widget/parent_box.dart';
import '../widget/posterity_box.dart';class TestStatefulWidget extends StatefulWidget {const TestStatefulWidget({super.key});@overrideState<TestStatefulWidget> createState() => _TestStatefulWidgetState();
}class _TestStatefulWidgetState extends State<TestStatefulWidget> {@overrideWidget build(BuildContext context) {return Scaffold(body: SizedBox(width: MediaQuery.of(context).size.width,height: MediaQuery.of(context).size.height,child: const Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [ParentBox(arguments: {'size': 260,'content': '父级',}),ChildBox(arguments: {'size': 200,'content': '子级',}),PosterityBox(arguments: {'size': 150,'content': '子孙级',}),],),),);}}
import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/widget/school_box.dart';
import 'package:flutter_widget_extends/widget/student_box.dart';
import 'package:flutter_widget_extends/widget/teacher_box.dart';class TestStatelessWidget extends StatefulWidget {const TestStatelessWidget({super.key});@overrideState<TestStatelessWidget> createState() => _TestStatelessWidgetState();
}class _TestStatelessWidgetState extends State<TestStatelessWidget> {@overrideWidget build(BuildContext context) {return Scaffold(body: SizedBox(width: MediaQuery.of(context).size.width,height: MediaQuery.of(context).size.height,child: const Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [SchoolBox(arguments: {'size': 150,'content': '父级',}),TeacherBox(arguments: {'size': 200,'content': '子级',}),StudentBox(arguments: {'size': 260,'content': '子孙级',}),],),),);}}
import 'package:flutter/material.dart';
import 'package:flutter_widget_extends/page/test_stateful_widget.dart';
import 'package:flutter_widget_extends/page/test_stateless_widget.dart';void main() {runApp(const MyApp());
}class MyApp extends StatelessWidget {const MyApp({super.key});@overrideWidget build(BuildContext context) {return MaterialApp(debugShowCheckedModeBanner: false,title: 'Flutter Demo',theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),useMaterial3: true,),home: const MyHomePage(title: 'Flutter Demo Home Page'),);}
}class MyHomePage extends StatefulWidget {const MyHomePage({super.key, required this.title});final String title;@overrideState<MyHomePage> createState() => _MyHomePageState();
}class _MyHomePageState extends State<MyHomePage> {@overrideWidget build(BuildContext context) {return Scaffold(body: SizedBox(width: MediaQuery.of(context).size.width,height: MediaQuery.of(context).size.height,child: Column(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: [Padding(padding: const EdgeInsets.only(bottom: 16),child: ElevatedButton(onPressed: () {Navigator.push<void>(context,MaterialPageRoute<void>(builder: (BuildContext context) =>const TestStatefulWidget(),),);},child: const Text('TestStatefulWidget',style: TextStyle(fontSize: 16),),),),ElevatedButton(onPressed: () {Navigator.push<void>(context,MaterialPageRoute<void>(builder: (BuildContext context) =>const TestStatelessWidget(),),);},child: const Text('TestStatelessWidget',style: TextStyle(fontSize: 16),),)],),),);}
}

源码地址

GitHub - LanSeLianMa/flutter_widget_extends: Flutter组件 StatefulWidget、StatelessWidget 可继承写法

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/449113.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Oracle 面试题 | 08.精选Oracle高频面试题

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

正则表达式可视化工具regex-vis

什么是正则表达式 &#xff1f; 正则表达式是对字符串操作的一种逻辑公式&#xff0c;就是用事先定义好的一些特定字符、及这些特定字符的组合&#xff0c;组成一个“规则字符串”&#xff0c;这个“规则字符串”用来表达对字符串的一种过滤逻辑。【百度百科】 正则表达式用简短…

idea中找到所有的TODO

idea中找到所有的TODO &#xff08;1&#xff09;快捷键 Alt6 &#xff08;2&#xff09;View -> Tool Windows -> TODO

RabbitMQ之三种队列之间的区别及如何选型

目录 不同队列之间的区别 Classic经典队列 Quorum仲裁队列 Stream流式队列 如何使用不同类型的队列​ Quorum队列 Stream队列 不同队列之间的区别 Classic经典队列 这是RabbitMQ最为经典的队列类型。在单机环境中&#xff0c;拥有比较高的消息可靠性。 经典队列可以选…

搜索引擎评价指标及指标间的关系

目录 二分类模型的评价指标准确率(Accuracy,ACC)精确率(Precision,P)——预测为正的样本召回率(Recall,R)——正样本注意事项 P和R的关系——成反比F值F1值F值和F1值的关系 ROC&#xff08;Receiver Operating Characteristic&#xff09;——衡量分类器性能的工具AUC&#xff…

Redis(十)SpringBoot集成Redis

文章目录 连接单机mvnYMLController.javaRedisConfig.java 连接集群YML问题复现 RedisTemplate方式 连接单机 mvn <!--Redis--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</art…

量化交易学习4(投资组合基本认识)

1 如何衡量投资组合的收益率 1.1 投资组合收益率的计算方法 1.2 投资组合的绝对收益率和相对收益率 2 如何衡量投资组合的风险 2.1 风险的定义 风险是指在未来可能发生的不确定性事件所带来的潜在损失。 在投资领域中&#xff0c;风险通常指投资所面临的不确定性和潜在的损失…

《向量数据库指南》——Milvus Cloud半数使用问题是配置问题

“Milvus Cloud 配置用户名密码进行校验,需要怎么开启呢?” “这个服务通过 k8s 已经起来的,我在不想关闭他的情况下应该怎么修改配置文件呢?” “ etcd 如果独立部署的话,这块儿的配置有推荐的参考值吗?” Milvus Cloud 作为一个分布式向量数据库,除了自身有较多的…

Python中使用Opencv-python库绘制直线、矩形、圆、文本

Python中使用Opencv-python库绘制直线、矩形、圆、文字 在Python中使用Opencv-python绘制直线、矩形、圆、文本非常简单&#xff0c;分别使用到line、rectangle、circle、putText这几个函数&#xff0c;具体可以参考https://docs.opencv.org/4.9.0/d6/d6e/group__imgproc__dra…

jsp服装穿搭推荐系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 JSP 游戏网上商城系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0…

ubuntu 上安装和配置Apache2+Subversion

目录 一、安装Apache2和SVN 二、Apache2设置 三、subversion配置 四、创建仓库和设置权限 五、仓库备份和恢复 系统环境 Ubuntu Linux (20.04) apache2 Subversion(1.13.0) 一、安装Apache2和SVN 通过命令在线安装apache2和subversion apt-get install apache2 libap…

[Java]JDK 安装后运行环境的配置

这篇文章用于介绍jdk.exe安装之后的运行环境配置&#xff0c;以及如何检查是否安装成功 检查自己是否安装jdk环境&#xff0c;记住这个安装的改的路径: (应该要安装2个&#xff0c;一个是jdk,一个是jre) 安装后的在文件夹的样子(路径自定义&#xff0c;在java下面): 参考如下…