android - 如何在 Flutter 中模拟 Android 的 showAsAction ="ifRoom"?

标签 android dart menu flutter menuitem

在我的 Flutter 应用程序中,我有一个屏幕,它是一个带有 Scaffold 小部件的 MaterialApp 作为它的主页。

这个 Scaffold 的 appBar 属性是一个 AppBar 小部件,其 actions 属性填充了一些操作和一个用于容纳其余选项的弹出菜单。

问题是,据我了解 AppBar 的 child actions list 可以是通用小部件(它将作为操作添加)或 PopupMenuButton 的实例,在这种情况下,它将添加平台特定图标,当触发该图标时会打开 AppBar 弹出菜单。

在原生 Android 上,这不是它的工作方式。我只需要膨胀一个充满菜单项的菜单,每个项目要么可以被强制成为一个 Action ,要么被强制不是一个 Action ,或者具有特殊值“ifRoom”,这意味着“如果有空间,就成为一个 Action ,否则是弹出菜单中的一个项目”。

Flutter 中有没有一种方法可以实现这种行为,而无需编写复杂的逻辑来填充 AppBar 的“ Action ”属性?

我已经查看了 AppBar 和 PopupMenuButton 文档,到目前为止还没有解释如何做这样的事情。我可以模拟这种行为,但随后我必须实际编写一个例程来计算可用空间并相应地构建“ Action ”列表。

这是一个典型的 Android 菜单,它混合了操作和弹出菜单条目。请注意,如果有空间,“load_game”条目可以是一个 Action ,如果没有空间,它将成为一个菜单条目。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game"
          android:showAsAction="always"/>
    <item android:id="@+id/load_game"
          android:icon="@drawable/ic_load_game"
          android:title="@string/load_game"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help"
          android:showAsAction="never" />
</menu>

另一方面,在 Flutter 中,我必须提前决定选项是 Action 还是菜单条目。

AppBar(
  title: Text("My Incredible Game"),
  primary: true,
  actions: <Widget>[
    IconButton(
      icon: Icon(Icons.add),
      tooltip: "New Game",
      onPressed: null,
    ),
    IconButton(
      icon: Icon(Icons.cloud_upload),
      tooltip: "Load Game",
      onPressed: null,
    ),
    PopupMenuButton(
      itemBuilder: (BuildContext context) {
        return <PopupMenuEntry>[
          PopupMenuItem(
            child: Text("Help"),
          ),
        ];
      },
    )
  ],
)

我希望能起作用的是 AppBar 实际上只有一个“ Action ”属性而不是“ Action ”。该属性只是一个允许我拥有任何东西的小部件,所以如果我只想要一个操作列表,那么一个充满 IconButton 的行就足够了。

除此之外,PopupMenuButton 内的每个 PopupMenuItem 都会有一个“showAsAction”属性。如果 PopupMenuButton 中的一个或多个 PopupMenuItem 被选中为操作或“ifRoom”并且有空间,则 PopupMenuButton 将水平扩展并将这些项目作为操作放置。

最佳答案

开箱即用不支持此功能,但您可以复制该行为。我创建了以下小部件:

import 'package:flutter/material.dart';

class CustomActionsRow extends StatelessWidget {
  final double availableWidth;
  final double actionWidth;
  final List<CustomAction> actions;

  const CustomActionsRow({
    @required this.availableWidth,
    @required this.actionWidth,
    @required this.actions,
  });

  @override
  Widget build(BuildContext context) {
    actions.sort(); // items with ShowAsAction.NEVER are placed at the end

    List<CustomAction> visible = actions
        .where((CustomAction customAction) => customAction.showAsAction == ShowAsAction.ALWAYS)
        .toList();

    List<CustomAction> overflow = actions
        .where((CustomAction customAction) => customAction.showAsAction == ShowAsAction.NEVER)
        .toList();

    double getOverflowWidth() => overflow.isEmpty ? 0 : actionWidth;

    for (CustomAction customAction in actions) {
      if (customAction.showAsAction == ShowAsAction.IF_ROOM) {
        if (availableWidth - visible.length * actionWidth - getOverflowWidth() > actionWidth) { // there is enough room
          visible.insert(actions.indexOf(customAction), customAction); // insert in its given position
        } else { // there is not enough room
          if (overflow.isEmpty) {
            CustomAction lastOptionalAction = visible.lastWhere((CustomAction customAction) => customAction.showAsAction == ShowAsAction.IF_ROOM, orElse: () => null);
            if (lastOptionalAction != null) {
              visible.remove(lastOptionalAction); // remove the last optionally visible action to make space for the overflow icon
              overflow.add(lastOptionalAction);
              overflow.add(customAction);
            } // else the layout will overflow because there is not enough space for all the visible items and the overflow icon
          } else {
            overflow.add(customAction);
          }
        }
      }
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        ...visible.map((CustomAction customAction) => customAction.visibleWidget),
        if (overflow.isNotEmpty) PopupMenuButton(
          itemBuilder: (BuildContext context) => [
            for (CustomAction customAction in overflow) PopupMenuItem(
              child: customAction.overflowWidget,
            )
          ],
        )
      ],
    );
  }
}

class CustomAction implements Comparable<CustomAction> {
  final Widget visibleWidget;
  final Widget overflowWidget;
  final ShowAsAction showAsAction;

  const CustomAction({
    this.visibleWidget,
    this.overflowWidget,
    @required this.showAsAction,
  });

  @override
  int compareTo(CustomAction other) {
    if (showAsAction == ShowAsAction.NEVER && other.showAsAction == ShowAsAction.NEVER) {
      return 0;
    } else if (showAsAction == ShowAsAction.NEVER) {
      return 1;
    } else if (other.showAsAction == ShowAsAction.NEVER) {
      return -1;
    } else {
      return 0;
    }
  }
}

enum ShowAsAction {
  ALWAYS,
  IF_ROOM,
  NEVER,
}
您需要指出所有图标(包括溢出图标)的总可用宽度,以及每个操作的宽度(它们都需要具有相同的宽度)。这是一个使用它的例子:
return Scaffold(
  appBar: AppBar(
    title: const Text("Title"),
    actions: <Widget>[
      CustomActionsRow(
        availableWidth: MediaQuery.of(context).size.width / 2, // half the screen width
        actionWidth: 48, // default for IconButtons
        actions: [
          CustomAction(
            overflowWidget: GestureDetector(
              onTap: () {},
              child: const Text("Never 1"),
            ),
            showAsAction: ShowAsAction.NEVER,
          ),
          CustomAction(
            visibleWidget: IconButton(
              onPressed: () {},
              icon: Icon(Icons.ac_unit),
            ),
            showAsAction: ShowAsAction.ALWAYS,
          ),
          CustomAction(
            visibleWidget: IconButton(
              onPressed: () {},
              icon: Icon(Icons.cancel),
            ),
            overflowWidget: GestureDetector(
              onTap: () {},
              child: const Text("If Room 1"),
            ),
            showAsAction: ShowAsAction.IF_ROOM,
          ),
          CustomAction(
            visibleWidget: IconButton(
              onPressed: () {},
              icon: Icon(Icons.ac_unit),
            ),
            showAsAction: ShowAsAction.ALWAYS,
          ),
          CustomAction(
            visibleWidget: IconButton(
              onPressed: () {},
              icon: Icon(Icons.cancel),
            ),
            overflowWidget: GestureDetector(
              onTap: () {},
              child: const Text("If Room 2"),
            ),
            showAsAction: ShowAsAction.IF_ROOM,
          ),
          CustomAction(
            overflowWidget: GestureDetector(
              onTap: () {},
              child: const Text("Never 2"),
            ),
            showAsAction: ShowAsAction.NEVER,
          ),
        ],
      ),
    ],
  ),
);
请注意,我没有添加任何断言,但您应该始终提供 visibleWidget对于 showAsAction 的操作是 ALWAYSIF_ROOM ,并始终提供 overflowWidget对于 showAsAction 的操作是 IF_ROOMNEVER .
这是使用上面代码的结果:
enter image description here
enter image description here
您可以自定义CustomActionsRow根据您的要求,例如,您可能有不同宽度的操作,在这种情况下,您需要每个 CustomAction提供自己的宽度等。

关于android - 如何在 Flutter 中模拟 Android 的 showAsAction ="ifRoom"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433298/

相关文章:

flutter - Sembast-删除 map 中的值

ios - 如何修复 [!] 在 .symlinks/plugins/sms_maintained/ios 中找不到 sms_maintained 的 podspec

android - 显示操作栏菜单按钮

Wordpress CSS Main Navigation .current-menu-item 变换 :

javascript - 滑动菜单一下子全部出来

java - APK 扩展文件和 APK 大小

android - 创建 SharedPreference 类的新对象并在 android 中调用函数

Android rawQuery 结果检查

java - 使用和/或提取可扩展文件 (obb) android

javascript - 如何以 Dart 语言将变量完全转储/打印到控制台?