[Flutter] 扩展一个支持弹出菜单的IconButton

Flutter有很多的基础Widget,其中IconButton很常用,还有 PopupButton, 这里扩展的这个 AppBarButton 是将两者融合一起,用起来更方便了。

import 'package:flutter/material.dart';

class AppBarButton<T> extends StatelessWidget {
  final Widget child;
  final Color color, focusColor;
  final double iconSize;
  final String tooltip;
  final bool autofocus;
  /// 菜单列表
  ///
  /// [[{'title': '分享', 'icon': FIcons.share_2, 'type': SHARE}]]
  final List<Map<String, dynamic>> menus;
  final Offset menuOffset;
  final MenusWidgetBuilder<T> menuItemBuilder;
  final T menuInitialValue;
  final T menuSelected;
  final double minWidth, splashRadius;
  final EdgeInsetsGeometry padding;
  final VoidCallback onPressed;
  final ValueChanged<T> onSelected;

  const AppBarButton({Key key, Widget child, Widget icon, this.color,
    this.focusColor, this.iconSize, this.tooltip,
    this.minWidth, this.splashRadius,
    this.autofocus,
    this.menus,
    this.menuOffset,
    this.menuItemBuilder,
    this.menuInitialValue,
    this.menuSelected,
    this.onSelected,
    this.padding, VoidCallback onPressed, VoidCallback onTap}):
      child = child ?? icon,
      onPressed = onPressed ?? onTap,
      super(key: key);

  @override
  Widget build(BuildContext context) {
    if ((menus != null && menus.isNotEmpty) || menuItemBuilder != null)
      return _buildButton(context, () {
        showButtonMenu(context,
          menus: menus,
          menuItemBuilder: menuItemBuilder,
          menuInitialValue: menuInitialValue,
          menuOffset: menuOffset,
          menuSelected: menuSelected,
          onSelected: onSelected
        );
      });
    return _buildButton(context, onPressed);
  }

  Widget _buildButton(BuildContext context, VoidCallback onPressed) {
    final _btn = IconButton(
      iconSize: iconSize ?? Theme.of(context).appBarTheme.iconTheme.size,
      icon: child,
      autofocus: autofocus ?? false,
      focusColor: focusColor,
      tooltip: tooltip,
      color: color,
      splashRadius: splashRadius,
      padding: padding ?? const EdgeInsets.all(8.0),
      onPressed: onPressed,
    );
    return minWidth == null ? _btn : ButtonTheme(
      minWidth: minWidth,
      child: _btn,
    );
  }

  /// 显示弹出菜单
  static void showButtonMenu<T>(BuildContext context, {
    Offset menuOffset,
    Offset local,
    List<Map<String, dynamic>> menus,
    MenusWidgetBuilder<T> menuItemBuilder,
    T menuInitialValue,
    T menuSelected,
    ValueChanged<T> onSelected,
    VoidCallback onMenuCancel,
  }) {
    final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context);
    final RenderBox button = context.findRenderObject() as RenderBox;
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(
        local != null ? local : button.localToGlobal(menuOffset ?? Offset(0, 40), ancestor: overlay),
        button.localToGlobal(button.size.bottomRight(Offset.zero), ancestor: overlay),
      ),
      Offset.zero & overlay.size,
    );
    final _primaryColor = Theme.of(context).primaryColor;
    final _textStyle = Theme.of(context).popupMenuTheme?.textStyle ??
        Theme.of(context).textTheme.subtitle1;
    final List<PopupMenuEntry<T>> items = menuItemBuilder != null 
        ? menuItemBuilder(context)
        : menus.map((element) {
          final _value = element['type'];
          return PopupMenuItem<T>(
            textStyle: _textStyle,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                (menuSelected == _value)
                  ? DefaultTextStyle(
                    style: _textStyle.copyWith(color: _primaryColor),
                    child: Text(element['title']))
                  : Text(element['title']),
                if (element['icon'] != null)
                  Icon(element['icon'], color: _primaryColor, size: 20),
              ],
            ),
            value: _value,
          );
    }).toList();
    // Only show the menu if there is something to show
    if (items.isNotEmpty) {
      showMenu<T>(
        context: context,
        elevation: popupMenuTheme.elevation,
        items: items,
        position: position,
        shape: popupMenuTheme.shape,
        color: popupMenuTheme.color,
        initialValue: menuInitialValue,
      ).then<void>((T newValue) {
        if (newValue == null) {
          if (onMenuCancel != null) onMenuCancel();
          return null;
        }
        if (onSelected != null)
          onSelected(newValue);
        return newValue;
      });
    }
  }
}

typedef MenusWidgetBuilder<T> = List<PopupMenuEntry<T>> Function(BuildContext context);

 

使用示例:

AppBarButton(
  icon: Icon(FIcons.save),
  iconSize: 21,
  tooltip: "保存",
  onPressed: () => _saveRule(context),
),

AppBarButton(
  icon: Icon(FIcons.share_2),
  tooltip: "分享",
  menus:  [
    {'title': '分享', 'icon': FIcons.share_2, 'type': SHARE},
    {'title': '扫码分享到远程', 'icon': FIcons.bscan, 'type': SHARE_QRSCAN},
  ],
  onSelected: (value) => onPopupMenuClick(value, provider),
),

AppBarButton<SourceSortType>(
  icon: Icon(Icons.sort_by_alpha),
  tooltip: "排序",
  menus: [
    {'title': '按类型',
      'icon': _type == SourceSortType.type ? _axisIcon : null,
      'type': SourceSortType.type},
    {'title': '按名称',
      'icon': _type == SourceSortType.name ? _axisIcon : null,
      'type': SourceSortType.name},
    {'title': '按作者',
      'icon': _type == SourceSortType.author ? _axisIcon : null,
      'type': SourceSortType.author},
    {'title': '按分组',
      'icon': _type == SourceSortType.group ? _axisIcon : null,
      'type': SourceSortType.group},
    {'title': '按修改时间',
      'icon': _type == SourceSortType.updateTime ? _axisIcon : null,
      'type': SourceSortType.updateTime},
    {'title': '按创建时间',
      'icon': _type == SourceSortType.createTime ? _axisIcon : null,
      'type': SourceSortType.createTime},
  ],
  menuSelected: _type,
  onSelected: (value) {
    provider.sort(value, _profile)
        .whenComplete(() => refreshData(provider));
  },
)

 

原文地址:https://www.cnblogs.com/yangyxd/p/14026104.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


简介 java中使用jar包来封装有用的功能,然后将其分发到maven仓库中,供其他人使用。同样的在dart中也有类似的概念叫做packages。packages就是可以用来共享的软件包,可以包含libraries和tools。 你可以在pub.dev网站中查到dart中所有的共享packages的
简介 flutter是google在2015年dart开发者峰会上推出的一种开源的移动UI构建框架,使用flutter可以非常方便的编译成运行在原始android,ios,web等移动平台上的移动应用。 flutter是使用dart来编写的,最新的flutter版本是2.5.3,而最新的Dart语言
简介 dart作为一种面向对象的语言,class是必不可少的。dart中所有的class,除了Null都继承自Object class。 要想使用dart中的类就要构造类的实例,在dart中,一个类的构造函数有两种方式,一起来看看吧。 传统的构造函数 和JAVA一样,dart中可以使用和class名
简介 Exception是程序中的异常情况,在JAVA中exception有checked Exception和unchecked Exception。那么在dart中的情况是不是一样的呢?一起来看看吧。 Exception和Error Dart中表示异常的类有两个,分别是Exception和Err
简介 虽然dart中的类只能有一个父类,也就是单继承的,但是dart提供了mixin语法来绕过这样限制。 今天,和大家一起来探讨一下dart类中的继承。 使用extends 和JAVA一样,dart中可以定义一个父类,然后使用extends来继承他,得到一个子类,如下所示: class Studen
简介 pubspec.yaml是所有dart项目的灵魂,它包含了所有dart项目的依赖信息和其他元信息,所以pubspec.yaml就是dart项目的meta! pubspec.yaml支持的字段 根据dart的定义,pubspec.yaml中可以包含下面的字段: 字段名 是否必须字段 描述 nam
dart系列之:dart语言中的特殊操作符 简介 有运算就有操作符,dart中除了普通的算术运算的操作符之外,还有自定义的非常特殊的操作符,今天带大家一起来探索一下dart中的特殊操作符。 普通操作符 普通操作符就很好解释了,就是加减乘除,逻辑运算符,比较运算符和位运算符等。 这些操作符和其他语言的
简介 在dart系统中,有pubspec.yaml文件的应用就可以被成为一个package。而Libray package是一类特殊的package,这种包可以被其他的项目所依赖. 也就是通常所说的库。 如果你也想你写的dart程序可以上传到pub.dev上,或者提供给别人使用,则来看看这篇文章吧。
简介 和所有的编程语言一样,dart有他内置的语言类型,这些内置类型都继承自Object,当然这些内置类型是dart语言的基础,只有掌握了这些内置类型才能够在使用dart语言的时候得心应手。 今天就给大家讲解一下dart语言的内置类型。 Null 在dart中用null来表示空。那么null和Nul
简介 函数是所有编程语言都有的内容,不管是面向对象还是面向过程,函数都是非常重要的一部分。dart中的函数和java中的函数有什么区别呢? dart作为一种面向对象的编程语言,它的函数也是一个对象,用Function来表示。先看下函数的定义: abstract class Function { ex
简介 熟悉JAVA的朋友可能知道,JAVA在8中引入了泛型的概念。什么是泛型呢?泛型就是一种通用的类型格式,一般用在集合中,用来指定该集合中应该存储的对象格式。 有了泛型可以简化我们的编程,并且可以减少错误的产生,非常的方便。 dart语言中也有泛型。一起来看看吧。 为什么要用泛型 使用泛型的主要目
简介 熟悉javascript的朋友应该知道,在ES6中引入了await和async的语法,可以方便的进行异步编程,从而摆脱了回调地狱。dart作为一种新生的语言,没有理由不继承这种优秀的品质。很自然的,dart中也有await和async语言,一起来看看吧。 为什么要用异步编程 那么为什么要用异步
简介 要想熟悉一种语言,最简单的做法就是熟悉dart提供的各种核心库。dart为我们提供了包括dart:core,dart:async,dart:math,dart:convert,dart:html和dart:io这几种常用的库。 今天给大家介绍一下dart:core中的数字和字符串的使用。 数字
简介 ES6中在引入异步编程的同时,也引入了Generators,通过yield关键词来生成对应的数据。同样的dart也有yield关键词和生成器的概念。 什么时候生成器呢?所谓生成器就是一个能够持续产生某些数据的装置,也叫做generator。 两种返回类型的generator 根据是同步生成还是
简介 Flutter的基础是widget,根据是否需要跟用户进行交互,widget则可以分为StatelessWidget和StatefulWidget。StatelessWidget只能根据传入的状态进行简单的初始化widget,如果要实现跟用户交互这种复杂的功能,则需要用到StatefulWid
简介 时间和日期是我们经常会在程序中使用到的对象。但是对时间和日期的处理因为有不同时区的原因,所以一直以来都不是很好用。就像在java中,为时间和日期修改和新增了多次API,那么作为新生的语言dart而言,会有什么不一样的地方吗? dart中关于日期和时间的两个非常重要的类是DateTime和Dur
简介 Library是dart用来组织代码的一种非常有用的方式,通过定义不同的Library,可以将非常有用的dart代码进行封装,从而提供给其他的项目使用。虽然我们可以自由使用import或者export来对library进行导入和导入。但是什么样的用法才是最合适的用法呢? 一起来看看吧。 使用p
简介 dart中的集合有三个,分别是list,set和map。dart在dart:core包中提供了对于这三种集合非常有用的方法,一起来看看吧。 List的使用 首先是list的创建,可以创建空的list或者带值的list: var emptyList =[]; var nameList = [&#
简介 dart:html包为dart提供了构建浏览器客户端的一些必须的组件,之前我们提到了HTML和DOM的操作,除了这些之外,我们在浏览器端另一个常用的操作就是使用XMLHttpRequest去做异步HTTP资源的请求,也就是AJAX请求。 dart同样提供了类似JS中XMLHttpRequest
简介 Flutter是google开发的一个跨平台的UI构建工具,flutter目前最新的版本是3.0.5。使用flutter你可以使用一套代码搭建android,IOS,web和desktop等不同平台的应用。做到一次编写到处运行的目的。 说到一次编写处处运行,大家可能会想到java。那么flut