flutter - 点击事件(一) - 自定义一个方便的点击控件

本文探讨了在Flutter中如何自定义点击控件,以增强可控性和复用性。通过示例代码展示了如何实现双击事件,并解释了在特定设备上应用不同点击效果的方法,遵循Flutter的组合优于继承的设计理念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android中,所有View都可以直接setOnClickListener, RN中也有TouchableHightlight这样的控件可以直接套在外面,ios中也可以有UIControl 这样的控件可以直接添加点击事件.

那么flutter中有吗? 答案自然是有. GestureDetector,InkResponse,InkWell, 包括一些琳琅满目的按钮,比如FlatButton,MaterialButton,CupertinoButton,IconButton,ImageButton 这些组件都可以达到目的. 那么自定义的目的是什么呢?

自定义的优点

最重要的自然就是可控性强,复用性强. 一次修改终身受用.
来看下面的这段代码

import 'package:flutter/material.dart';

class MaterialTapWidget extends StatelessWidget {
   
  final double radius;
  final Function onTap;
  final Widget child;
  final double elevation;
  final Color backgroundColor;
  final Color splashColor;
  final Function onLongTap;

  const MaterialTapWidget({
   
    Key key,
    this.radius = 0.0,
    this.onTap,
    this.onLongTap,
    @required this.child,
    this.splashColor,
    this.elevation = 0.0,
    this.backgroundColor = Colors.transparent,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
   
    Widget w = ClipRRect(
      borderRadius: BorderRadius.circular(radius),
      child: Material(
        borderRadius: BorderRadius.circular(radius),
        color: backgroundColor,
        elevation: 0.0,
        child: InkWell(
          child: child,
          onTap: onTap,
          onLongPress: onLongTap,
        ),
      ),
    );

    if (this.splashColor != null) {
   
      return Theme(
        data: Theme.of(context).copyWith(splashColor: this.splashColor),
        child: w
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值