Flutter可扩展浮动操作按钮插件flutter_expandable_fab的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter可扩展浮动操作按钮插件flutter_expandable_fab的使用

flutter_expandable_fab是一个能够动画显示和隐藏多个操作按钮的速度拨号FAB(浮动操作按钮)。它可以配置为垂直、水平或扇形方式显示,位于任意一侧,并允许精细的自定义。

快速开始

添加依赖

首先,在你的pubspec.yaml文件中添加flutter_expandable_fab作为依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_expandable_fab: ^2.0.0 # 请检查最新版本

然后运行flutter pub get来安装依赖。

基本用法

以下是一个简单的例子,展示了如何在应用中使用ExpandableFab:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Expandable FAB Example'),
        ),
        body: Center(
          child: Text('Press the floating action button!'),
        ),
        floatingActionButtonLocation: ExpandableFab.location,
        floatingActionButton: ExpandableFab(
          children: [
            FloatingActionButton.small(
              heroTag: null,
              child: Icon(Icons.edit),
              onPressed: () {},
            ),
            FloatingActionButton.small(
              heroTag: null,
              child: Icon(Icons.search),
              onPressed: () {},
            ),
          ],
        ),
      ),
    );
  }
}

自定义打开/关闭按钮

你可以通过设置openButtonBuildercloseButtonBuilder来自定义打开和关闭按钮。例如:

ExpandableFab(
  openButtonBuilder: RotateFloatingActionButtonBuilder(
    child: Icon(Icons.account_box),
    fabSize: ExpandableFabSize.regular,
    foregroundColor: Colors.amber,
    backgroundColor: Colors.green,
    shape: CircleBorder(),
  ),
  closeButtonBuilder: DefaultFloatingActionButtonBuilder(
    child: Icon(Icons.close),
    fabSize: ExpandableFabSize.small,
    foregroundColor: Colors.deepOrangeAccent,
    backgroundColor: Colors.lightGreen,
    shape: CircleBorder(),
  ),
  children: [
    // 子按钮
  ],
)

打开/关闭菜单

如果你需要程序化地控制菜单的打开和关闭,可以使用GlobalKey<ExpandableFabState>来获取状态并调用toggle()方法:

final _key = GlobalKey<ExpandableFabState>();

// ...

floatingActionButton: ExpandableFab(
  key: _key,
  children: [
    FloatingActionButton.small(
      child: Icon(Icons.edit),
      onPressed: () {
        final state = _key.currentState;
        if (state != null) {
          debugPrint('isOpen:${state.isOpen}');
          state.toggle();
        }
      },
    ),
  ],
),

更多属性

ExpandableFab提供了许多其他属性用于进一步定制其行为和外观,如distance, duration, fanAngle, type, pos, overlayStyle等。具体可以参考官方文档中的Properties部分。

完整示例

这里提供一个更完整的示例,结合了上述所有特性:

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FirstPage(),
    );
  }
}

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  final _key = GlobalKey<ExpandableFabState>();
  final scaffoldKey = GlobalKey<ScaffoldMessengerState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      body: Center(
        child: Text('Press the floating action button!'),
      ),
      floatingActionButtonLocation: ExpandableFab.location,
      floatingActionButton: ExpandableFab(
        key: _key,
        distance: 100,
        duration: Duration(milliseconds: 300),
        type: ExpandableFabType.up,
        pos: ExpandableFabPos.right,
        fanAngle: 90,
        overlayStyle: ExpandableFabOverlayStyle(
          color: Colors.black.withOpacity(0.5),
          blur: 5,
        ),
        onOpen: () => debugPrint('onOpen'),
        afterOpen: () => debugPrint('afterOpen'),
        onClose: () => debugPrint('onClose'),
        afterClose: () => debugPrint('afterClose'),
        openButtonBuilder: RotateFloatingActionButtonBuilder(
          child: Icon(Icons.add),
          fabSize: ExpandableFabSize.regular,
          foregroundColor: Colors.white,
          backgroundColor: Colors.blue,
          shape: CircleBorder(),
        ),
        closeButtonBuilder: DefaultFloatingActionButtonBuilder(
          child: Icon(Icons.close),
          fabSize: ExpandableFabSize.small,
          foregroundColor: Colors.white,
          backgroundColor: Colors.red,
          shape: CircleBorder(),
        ),
        children: [
          FloatingActionButton.small(
            heroTag: null,
            child: Icon(Icons.edit),
            onPressed: () {
              scaffoldKey.currentState?.showSnackBar(SnackBar(content: Text("Edit")));
            },
          ),
          FloatingActionButton.small(
            heroTag: null,
            child: Icon(Icons.search),
            onPressed: () {
              Navigator.of(context).push(MaterialPageRoute(builder: (_) => NextPage()));
            },
          ),
          FloatingActionButton.small(
            heroTag: null,
            child: Icon(Icons.share),
            onPressed: () {
              final state = _key.currentState;
              if (state != null) {
                debugPrint('isOpen:${state.isOpen}');
                state.toggle();
              }
            },
          ),
        ],
      ),
    );
  }
}

class NextPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Next Page')),
      body: Center(child: Text('This is the next page.')),
    );
  }
}

这个例子展示了如何创建一个带有三个子按钮的可扩展浮动操作按钮,这些子按钮分别执行编辑、搜索和分享功能。同时,它还演示了如何通过点击主按钮来打开/关闭菜单以及导航到新页面的功能。


更多关于Flutter可扩展浮动操作按钮插件flutter_expandable_fab的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter可扩展浮动操作按钮插件flutter_expandable_fab的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_expandable_fab插件的一个详细代码示例。这个插件允许你创建一个可扩展的浮动操作按钮(FAB),当用户点击它时,可以展开显示更多的选项。

首先,确保你已经在pubspec.yaml文件中添加了flutter_expandable_fab依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_expandable_fab: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个完整的示例代码,展示了如何使用flutter_expandable_fab

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Expandable FAB Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isOpened = false;

  void toggleFAB() {
    setState(() {
      isOpened = !isOpened;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Expandable FAB Demo'),
      ),
      body: Center(
        child: Text('Tap the FAB to expand or collapse'),
      ),
      floatingActionButton: ExpandableFab(
        color: Colors.blue,
        icon: AnimatedIcons.menu_arrow,
        // 初始是否展开
        isOpened: isOpened,
        // 展开回调
        onPress: () {
          toggleFAB();
        },
        // 收缩回调
        onCollapse: () {
          toggleFAB();
        },
        // 子按钮
        expandedChildren: <Widget>[
          FloatingActionButton(
            heroTag: '1',
            backgroundColor: Colors.red,
            onPressed: () {
              print('Option 1 clicked');
              toggleFAB(); // 点击后收缩FAB
            },
            child: Icon(Icons.add),
          ),
          FloatingActionButton(
            heroTag: '2',
            backgroundColor: Colors.green,
            onPressed: () {
              print('Option 2 clicked');
              toggleFAB(); // 点击后收缩FAB
            },
            child: Icon(Icons.edit),
          ),
          FloatingActionButton(
            heroTag: '3',
            backgroundColor: Colors.purple,
            onPressed: () {
              print('Option 3 clicked');
              toggleFAB(); // 点击后收缩FAB
            },
            child: Icon(Icons.delete),
          ),
        ],
      ),
    );
  }
}

代码解释

  1. 依赖导入

    import 'package:flutter/material.dart';
    import 'package:flutter_expandable_fab/flutter_expandable_fab.dart';
    
  2. 应用入口

    void main() {
      runApp(MyApp());
    }
    
  3. 主应用组件

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Expandable FAB Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(),
        );
      }
    }
    
  4. 主页组件

    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      bool isOpened = false;
    
      void toggleFAB() {
        setState(() {
          isOpened = !isOpened;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Expandable FAB Demo'),
          ),
          body: Center(
            child: Text('Tap the FAB to expand or collapse'),
          ),
          floatingActionButton: ExpandableFab(
            color: Colors.blue,
            icon: AnimatedIcons.menu_arrow,
            isOpened: isOpened,
            onPress: () {
              toggleFAB();
            },
            onCollapse: () {
              toggleFAB();
            },
            expandedChildren: <Widget>[
              FloatingActionButton(
                heroTag: '1',
                backgroundColor: Colors.red,
                onPressed: () {
                  print('Option 1 clicked');
                  toggleFAB();
                },
                child: Icon(Icons.add),
              ),
              FloatingActionButton(
                heroTag: '2',
                backgroundColor: Colors.green,
                onPressed: () {
                  print('Option 2 clicked');
                  toggleFAB();
                },
                child: Icon(Icons.edit),
              ),
              FloatingActionButton(
                heroTag: '3',
                backgroundColor: Colors.purple,
                onPressed: () {
                  print('Option 3 clicked');
                  toggleFAB();
                },
                child: Icon(Icons.delete),
              ),
            ],
          ),
        );
      }
    }
    

这个示例展示了如何创建一个包含三个子选项的可扩展FAB。当用户点击FAB时,它会展开显示这些选项,并且当用户点击任何一个子选项或再次点击FAB时,它会收缩。

回到顶部