【Flutter学习笔记】10.2 组合现有组件

news2024/9/22 19:24:55

参考资料: 《Flutter实战·第二版》 10.2 组合现有组件


在Flutter中页面UI通常都是由一些低级别组件组合而成,当我们需要封装一些通用组件时,应该首先考虑是否可以通过组合其他组件来实现,如果可以,则应优先使用组合,因为直接通过现有组件拼装会非常简单、灵活、高效。

10.2.1 实例:自定义渐变按钮

Flutter中自带的按钮组件不支持渐变背景,这里自定义一个GradientButton组件,具有下面的功能:

  1. 背景支持渐变色
  2. 手指按下时有涟漪效果
  3. 可以支持圆角
    自带的按钮组件是下面的效果:
    在这里插入图片描述
    其实除了不是渐变色背景其它都满足了。在Flutter中,ElevatedButton组件默认不具有圆角。然而,可以通过自定义其形状来为其添加圆角。可以在ElevatedButtonstyle属性中设置shape属性来实现:
ElevatedButton(  
      onPressed: () {  
        print('Button pressed!');  
      },  
      child: Text('Press Me'),  
      style: ElevatedButton.styleFrom(  
        primary: Colors.blue, // 设置按钮的主色  
        onPrimary: Colors.white, // 设置按钮上文字的颜色  
        shape: RoundedRectangleBorder( // 设置按钮的形状为圆角矩形  
          borderRadius: BorderRadius.circular(20.0), // 设置圆角的大小  
        ),  
      ),  
    )

在这里插入图片描述
想有渐变背景的话,不能通过style属性设置背景色,因为数据类型是有限制的。可以利用DecoratedBoxInkWell组合来实现,前者能够设置圆角和渐变背景色,后者可以提供涟漪效果。下面是实现代码,思路比较简单,主要是UI的绘制逻辑:

class GradientButton extends StatelessWidget {
  const GradientButton({Key? key, 
    this.colors,
    this.width,
    this.height,
    this.onPressed,
    this.borderRadius,
    required this.child,
  }) : super(key: key);

  // 渐变色数组
  final List<Color>? colors;

  // 按钮宽高
  final double? width;
  final double? height;
  final BorderRadius? borderRadius;

  //点击回调
  final GestureTapCallback? onPressed;

  final Widget child;

  
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);

    //确保colors数组不空
    List<Color> _colors =
        colors ?? [theme.primaryColor, theme.primaryColorDark];

    return DecoratedBox(
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: _colors),
        borderRadius: borderRadius,
        //border: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
      ),
      child: Material(
        type: MaterialType.transparency,
        child: InkWell(
          splashColor: _colors.last,
          highlightColor: Colors.transparent,
          borderRadius: borderRadius,
          onTap: onPressed,
          child: ConstrainedBox(
            constraints: BoxConstraints.tightFor(height: height, width: width),
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: DefaultTextStyle(
                  style: const TextStyle(fontWeight: FontWeight.bold),
                  child: child,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

需要注意组件的输入属性,按钮点击的回调为GestureTapCallback类型,其属性除了child之外,均为可选属性。其具有默认样式,如果没有传入color属性,则默认为主题色主色调和暗色调。通过ConstrainedBox可以定义按钮的大小,还可以设置默认的字体样式(这里可以按需求去掉)。
定义好之后就可以使用了,这里定义了三个不同的按钮,代码和效果如下:

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

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

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

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(
          widget.title,
          style: TextStyle(
              color: Colors.teal.shade800, fontWeight: FontWeight.w900),
        ),
        actions: [
          ElevatedButton(
            child: const Icon(Icons.refresh),
            onPressed: () {
              setState(() {});
            },
          )
        ],
      ),
      body: const ComponentTestRoute(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: Icon(
          Icons.add_box,
          size: 30,
          color: Colors.teal[400],
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

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

  
  ComponentTestRouteState createState() => ComponentTestRouteState();
}

class ComponentTestRouteState extends State<ComponentTestRoute> {
  
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            child: Padding(
          padding: const EdgeInsets.only(top: 80),
          child: Column(
            children: [
              GradientButton(
                colors: const [Colors.purple, Colors.red],
                height: 50.0,
                child: const Text("Submit"),
                onPressed: () {},
              ),
              GradientButton(
                height: 50.0,
                colors: [Colors.yellow, Colors.green.shade700],
                child: const Text("Submit"),
                onPressed: () {},
              ),
              GradientButton(
                height: 50.0,
                //borderRadius: const BorderRadius.all(Radius.circular(5)),
                colors: const [Colors.cyanAccent, Colors.blueAccent],
                child: const Text("Submit"),
                onPressed: () {},
              ),
            ],
          ),
        ))
      ],
    );
  }
}

class GradientButton extends StatelessWidget {
  const GradientButton({
    Key? key,
    this.colors,
    this.width,
    this.height,
    this.onPressed,
    this.borderRadius,
    required this.child,
  }) : super(key: key);

  // 渐变色数组
  final List<Color>? colors;

  // 按钮宽高
  final double? width;
  final double? height;
  final BorderRadius? borderRadius;

  //点击回调
  final GestureTapCallback? onPressed;

  final Widget child;

  
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);

    //确保colors数组不空
    List<Color> _colors =
        colors ?? [theme.primaryColor, theme.primaryColorDark];

    return DecoratedBox(
      decoration: BoxDecoration(
        gradient: LinearGradient(colors: _colors),
        borderRadius: borderRadius,
        //border: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
      ),
      child: Material(
        type: MaterialType.transparency,
        child: InkWell(
          splashColor: _colors.last,
          highlightColor: Colors.transparent,
          borderRadius: borderRadius,
          onTap: onPressed,
          child: ConstrainedBox(
            constraints: BoxConstraints.tightFor(height: height, width: width),
            child: Center(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: DefaultTextStyle(
                  style: const TextStyle(fontWeight: FontWeight.bold),
                  child: child,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

按下之后涟漪的颜色为colors中最后一个颜色:
在这里插入图片描述
虽然实现起来较为容易,但是在抽离出单独的组件时要考虑代码规范性,如必要参数要用required关键词标注,对于可选参数在特定场景需要判空设置默认值等。为了保证代码健壮性,我们需要在用户错误地使用组件时能够兼容或报错提示(使用assert断言函数)。

在Dart语言中,assert 是一种用于在开发过程中捕获错误的工具。assert 语句用于在调试模式下测试某个条件是否为真。如果条件为假,那么 assert 语句将抛出一个 AssertionError 异常,并停止程序的执行。这主要用于在开发过程中捕捉不应该发生的错误情况,从而帮助开发者定位问题。
assert 语句在发布模式(即生产环境)下会被忽略,因此不会影响最终用户的体验。这使得 assert 成为开发过程中进行条件测试的理想工具,而无需担心在最终应用中引入额外的性能开销或错误处理逻辑。

下面是assert在Dart中的基本用法:

void main() {  
  int number = 5;  
    
  // 使用 assert 语句检查 number 是否大于 0  
  assert(number > 0, 'number should be greater than 0');  
    
  // 如果条件为真,程序继续执行  
  print('Number is positive.');  
    
  // 如果条件为假,抛出 AssertionError,并显示提供的错误消息  
  // assert(number < 0, 'number should be less than 0'); // 这会抛出 AssertionError  
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Redis中的过期键删除策略

过期键删除策略 概述 数据库键的过期时间都保存在过期字典中&#xff0c;并且知道根据过期时间去判断一个键是否过期,剩下的问题是&#xff1a;如果一个键过期了&#xff0c;那么它什么时候会被删除呢? 这个问题有三种可能的答案&#xff0c;它们分别代表了三种不同的删除策…

阿里云国际该如何设置DDoS高防防护策略?

DDoS高防提供针对网络四层DDoS攻击的防护策略设置功能&#xff0c;例如虚假源和空连接检测、源限速、目的限速&#xff0c;适用于优化调整非网站业务的DDoS防护策略。在DDoS高防实例下添加端口转发规则&#xff0c;接入非网站业务后&#xff0c;您可以单独设置某个端口的DDoS防…

专题三 - 二分 - leetcode 704. 二分查找 | 简单难度

leetcode 704. 二分查找 leetcode 704. 二分查找 | 简单难度1. 题目详情1. 原题链接2. 基础框架 2. 解题思路1. 题目分析2. 算法原理3. 时间复杂度 3. 代码实现4. 知识与收获 leetcode 704. 二分查找 | 简单难度 1. 题目详情 给定一个 n 个元素有序的&#xff08;升序&#x…

3.3网安学习第三阶段第三周回顾(个人学习记录使用)

本周重点 ①渗透测试介绍 ②sqlmap注入扫描工具 ③XSS脚本注入 本周主要内容 ①渗透测试介绍 一、渗透测试 通过模拟黑客对系统进行攻击的手段或技术&#xff0c;在被测系统中发现漏洞的行为。除了提供漏洞之外&#xff0c;还需提供安全意见。 与黑站不同&#xff0c;渗…

仿牛客项目Day10——统一异常处理、记录日志

统一异常处理 在controller里创建advice包&#xff0c;创建ExceptionAdvice类 这个注解括号里面是指只扫描被Controller标注的bean 请求request、响应response、异常exception 普通请求和异步请求的区别在于传的是json还是html吗&#xff1f; 统一记录日志 面向切面编程&…

2024/03/21(网络编程·day7)

一、思维导图 二、 //定义删除函数 int do_delete(sqlite3 *ppDb) {int del_numb0;printf("请输入要删除的学生的学号:");scanf("%d",&del_numb);getchar();//准备sql语句char sql[128]"select *from Stu";sprintf(sql,"delete from …

RocketMQ 流存储解析:面向流场景的关键特性与典型案例

作者&#xff1a;林清山&#xff08;隆基&#xff09; 前言&#xff1a; 从初代开源消息队列崛起&#xff0c;到 PC 互联网、移动互联网爆发式发展&#xff0c;再到如今 IoT、云计算、云原生引领了新的技术趋势&#xff0c;消息中间件的发展已经走过了 30 多个年头。 目前&…

蓝桥杯-模拟-纸张尺寸

题目 思路 代码 qlist(str(input())) numint(q[1]) x,y1189,841 while num:num-1x//2if x<y:x,yy,x print(x) print(y)

关于安卓调用文件浏览器(一)打开并复制

背景 最近在做一个硬件产品&#xff0c;安卓应用开发。PM抽风&#xff0c;要求从app打开文件浏览器&#xff0c;跳转到指定目录&#xff0c;然后可以实现文件复制粘贴操作。 思考 从应用开发的角度看&#xff0c;从app打开系统文件浏览器并且选择文件&#xff0c;这是很常见…

牛客小白月赛86(D剪纸游戏)

题目链接:D-剪纸游戏_牛客小白月赛86 (nowcoder.com) 题目描述: 输入描述: 输入第一行包含两个空格分隔的整数分别代表 n 和 m。 接下来输入 n行&#xff0c;每行包含 m 个字符&#xff0c;代表残缺纸张。 保证&#xff1a; 1≤n,m≤10001 字符仅有 . 和 * 两种字符&#xf…

代码随想录算法训练营 DAY 16 | 104.二叉树最大深度 111.二叉树最小深度 222.完全二叉树的节点个数

104.二叉树最大深度 深度和高度 二叉树节点的深度&#xff1a;指从根节点到该节点的最长简单路径边的条数或者节点数&#xff08;取决于深度从0开始还是从1开始&#xff09;二叉树节点的高度&#xff1a;指从该节点到叶子节点的最长简单路径边的条数或者节点数&#xff08;取…

按键模拟精灵

按键模拟精灵功能简单&#xff1a; 1.添加模拟按键 2.删除模拟按键 3.开始模拟 4.停止模拟 适合简单的按键操作&#xff0c;有需要的可以点赞收藏关注我&#xff01;

315晚会:虚假的水军是怎样形成的?又要如何破解?

随着互联网的普及和发展&#xff0c;网络信息的传播已经成为了现代社会中不可或缺的一部分。然而&#xff0c;随之而来的是网络舆论的泛滥和虚假信息的肆意传播&#xff0c;这使得网络治理变得尤为重要。 2024年的315晚会&#xff0c;央视曝光了一种新型的水军制造手段&#x…

DXF™ 格式对象和图元——cad vba

在 DXF™ 格式中&#xff0c;对象的定义与图元的定义不同&#xff1a;对象没有图形表示&#xff0c;而图元则有图形表示。例如&#xff0c;词典是对象而不是图元。图元也称为图形对象&#xff0c;而对象称为非图形对象。 第七段中humbnail image&#xff0c;即&#xff1a;缩略…

【智能算法】海洋捕食者算法(MPA)原理及实现

目录 1.背景2.算法原理2.1算法思想2.2算法过程 3.结果展示4.参考文献 1.背景 2020年&#xff0c;Afshin Faramarzi 等人受到海洋生物适者生存启发&#xff0c;提出了海洋捕食者算法(Marine Predators Algorithm&#xff0c;MPA)。 2.算法原理 2.1算法思想 MPA根据模拟自然界…

图神经网络实战(2)——图论基础

图神经网络实战&#xff08;2&#xff09;——图论基础 0. 前言1. 图属性1.1 有向图和无向图1.2 加权图和非加权图1.3 连通图和非连通图1.4 其它图类型 2. 图概念2.1 基本对象2.2 图的度量指标2.2 邻接矩阵表示法 3. 图算法3.1 广度优先搜索3.2 深度优先搜索 小结系列链接 0. 前…

户外水质检测显示屏用于检测并显示各种水质数据

水质检测一直是环境保护和公共卫生领域的重要课题。随着科技的不断进步&#xff0c;水质检测设备也在不断更新换代。其中&#xff0c;水质检测显示屏作为一种新型的检测设备&#xff0c;为监测和显示各种水质数据提供了便利和高效的手段。 水质检测显示屏是一种集成了传感器、数…

tcp seq ack

seq&#xff08;Sequence Number&#xff09;&#xff1a;32bits&#xff0c;表示这个tcp包的序列号。tcp协议拼凑接收到的数据包时&#xff0c;根据seq来确定顺序&#xff0c;并且能够确定是否有数据包丢失。 ack&#xff08;Acknowledgment Number&#xff09;&#xff1a;3…

Python基础学习笔记(一)

Python简介 Python 语言是一种跨平台、开源、免费、解释型、面向对象、动态数据类型的高级程序设计语言。早期版本的 Python 被称作是 Python1&#xff1b;Python2 最后一个版本是 2.7&#xff1b;Python3 是目前最活跃的版 本&#xff0c;基本上新开发的 Python 代码都会支持…

Infoq:腾讯内容千亿级实时计算和规则引擎实践优化之路

1.系统背景 腾讯内容中台提供从内容生产、内容加工、内容分发、内容结算等全链路环节的一站式服务&#xff0c;在这个过程中&#xff0c;会产生大量的数据以及围绕这些数据衍生的实时流业务应用&#xff0c;如智能审核、运营决策、在线学习等&#xff0c;从底层去看这些内容生态…