Flutter模态顶部弹出层插件modal_top_sheet的使用

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

Flutter模态顶部弹出层插件modal_top_sheet的使用

[ModalTopSheet] 是一个用于创建顶部对齐的模态表单的 Flutter 插件。该插件扩展了 Flutter 中的模态表单功能,以允许更灵活和可定制的用户界面。效果类似于 [AppBar] 的下拉菜单。

特性

特性图

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  modal_top_sheet: ^0.0.1

使用

以下是一个完整的示例,展示了如何使用 modal_top_sheet 插件。

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.blue,
          foregroundColor: Colors.black,
          elevation: 0,
        ),
        scaffoldBackgroundColor: Colors.white,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  void openModal() async => showModalTopSheet(
        context,
        isDismissible: false,
        child: const YourModalWidget(),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWithSubtitle(
        titleSection: InkWell(
            onTap: openModal,
            child: const Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Top Modal Sheet Example',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                  ),
                ),
                Text(
                  'Tap to expand',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.black54,
                  ),
                ),
              ],
            )),
      ),
      body: CustomScrollView(
        slivers: [
          SliverList.builder(
            itemBuilder: (context, index) {
              return ListTile(
                title: Text('Item $index'),
              );
            },
            itemCount: 20,
          ),
        ],
      ),
    );
  }
}

class AppBarWithSubtitle extends StatelessWidget implements PreferredSizeWidget {
  const AppBarWithSubtitle({
    Key? key,
    required this.titleSection,
  }) : super(key: key);
  final Widget titleSection;

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    return Align(
      alignment: Alignment.topCenter,
      child: SafeArea(
        bottom: false,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Flexible(
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxHeight: kToolbarHeight),
                child: CustomSingleChildLayout(
                  delegate: const _ToolbarContainerLayout(kToolbarHeight),
                  child: Container(
                    color: theme.appBarTheme.backgroundColor,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                      child: Row(
                        children: [
                          Expanded(child: titleSection),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

class _ToolbarContainerLayout extends SingleChildLayoutDelegate {
  const _ToolbarContainerLayout(this.toolbarHeight);

  final double toolbarHeight;

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return constraints.tighten(height: toolbarHeight);
  }

  @override
  Size getSize(BoxConstraints constraints) {
    return Size(constraints.maxWidth, toolbarHeight);
  }

  @override
  Offset getPositionForChild(Size size, Size childSize) {
    return Offset(0.0, size.height - childSize.height);
  }

  @override
  bool shouldRelayout(_ToolbarContainerLayout oldDelegate) => toolbarHeight != oldDelegate.toolbarHeight;
}

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

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    return ConstrainedBox(
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.4,
        ),
        child: Column(
          children: [
            Container(
              constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.4 - 60,
              ),
              color: Colors.blue,
              child: ListView.builder(
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('Modal Item $index'),
                    onTap: () {
                      Navigator.pop(context);
                    },
                  );
                },
                itemCount: 2,
              ),
            ),
            ClipPath(
              clipper: WaveClipper(),
              child: Container(
                color: theme.appBarTheme.backgroundColor,
                height: 60,
                child: Center(
                  child: CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.black54,
                    child: IconButton(
                      onPressed: () => Navigator.pop(context),
                      icon: const Icon(Icons.close),
                      color: Colors.blue,
                      iconSize: 20,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
  }
}

class WaveClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(0, size.height / 2);
    path.conicTo(size.width / 8, size.height * 0.5, size.width / 3, size.height * 0.75, 0.5);
    path.quadraticBezierTo(
        size.width / 2, size.height, size.width * 2 / 3, size.height * 0.75);
    path.conicTo(size.width * 0.875, size.height * 0.5, size.width, size.height * 0.5, 0.5);
    path.lineTo(size.width, 0);
    path.lineTo(0, 0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
    return false;
  }
}

完整的示例代码可以在 /example 文件夹中找到。


更多关于Flutter模态顶部弹出层插件modal_top_sheet的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter模态顶部弹出层插件modal_top_sheet的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用modal_top_sheet插件的示例代码。这个插件允许你在屏幕顶部显示一个模态弹出层,类似于iOS中的Action Sheet。首先,确保你已经在pubspec.yaml文件中添加了modal_top_sheet依赖:

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

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

以下是一个完整的示例,展示如何使用modal_top_sheet插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Modal Top Sheet Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  void _showModalTopSheet(BuildContext context) {
    showMaterialTopSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16),
              topRight: Radius.circular(16),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                'Select an option',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 16.0),
              ListTile(
                leading: Icon(Icons.star),
                title: Text('Option 1'),
                onTap: () {
                  Navigator.pop(context);
                  // 处理Option 1的点击事件
                  print('Option 1 selected');
                },
              ),
              ListTile(
                leading: Icon(Icons.star_border),
                title: Text('Option 2'),
                onTap: () {
                  Navigator.pop(context);
                  // 处理Option 2的点击事件
                  print('Option 2 selected');
                },
              ),
              ListTile(
                leading: Icon(Icons.cancel),
                title: Text('Cancel'),
                onTap: () {
                  Navigator.pop(context);
                  // 处理取消点击事件
                  print('Cancel selected');
                },
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Modal Top Sheet Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _showModalTopSheet(context),
          child: Text('Show Modal Top Sheet'),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,包含一个按钮。点击按钮时,会调用_showModalTopSheet函数来显示模态顶部弹出层。弹出层包含三个选项:Option 1、Option 2和Cancel,每个选项点击后都会执行相应的操作并关闭弹出层。

showMaterialTopSheet函数是modal_top_sheet插件提供的一个便捷方法,用于显示模态顶部弹出层。你可以根据自己的需求自定义弹出层的内容和样式。

回到顶部