Flutter侧边栏导航插件sidebarx的使用

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

Flutter侧边栏导航插件SidebarX的使用

SidebarX 🔥

Flutter多平台导航侧边栏/侧导航栏/抽屉小部件

显示一些❤️并在GitHub上为该项目加星以支持项目!

Mobile Desktop Web
Image Image Image

Pub Star on Github License: MIT

Getting started

Add dependency

pubspec.yaml文件中添加依赖:

dependencies:
  sidebarx: ^0.17.1

Add import package

在Dart文件中导入包:

import 'package:sidebarx/sidebarx.dart';

Easy to use

该包设计时充分考虑了大屏幕的适应性。因此,将小部件添加到您的屏幕将会非常简单。

Scaffold(
  body: Row(
    children: [
      SidebarX(
        controller: SidebarXController(selectedIndex: 0),
        items: const [
          SidebarXItem(icon: Icons.home, label: 'Home'),
          SidebarXItem(icon: Icons.search, label: 'Search'),
        ],
      ),
      // Your app screen body
    ],
  ),
)

Use with small mobile screens

在小屏幕和移动设备上,您可以将现成的Sidebar小部件用作应用程序的抽屉,以获得出色的用户体验。否则,保留代码不变即可获得相同的体验。

Scaffold(
  drawer: SidebarX(
    controller: SidebarXController(selectedIndex: 0, extended: true),
    items: const [
      SidebarXItem(icon: Icons.home, label: 'Home'),
      SidebarXItem(icon: Icons.search, label: 'Search'),
    ],
  ),
  body: const Center(child: Text('Your app body')),
)

Additional information

项目正在开发中,欢迎您的pull-requests和issues 👍感谢您的支持 ❤️

示例代码

下面是一个完整的示例demo,展示了如何使用sidebarx插件创建一个带有侧边栏的应用程序:

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

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

class SidebarXExampleApp extends StatelessWidget {
  SidebarXExampleApp({Key? key}) : super(key: key);

  final _controller = SidebarXController(selectedIndex: 0, extended: true);
  final _key = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SidebarX Example',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: primaryColor,
        canvasColor: canvasColor,
        scaffoldBackgroundColor: scaffoldBackgroundColor,
        textTheme: const TextTheme(
          headlineSmall: TextStyle(
            color: Colors.white,
            fontSize: 46,
            fontWeight: FontWeight.w800,
          ),
        ),
      ),
      home: Builder(
        builder: (context) {
          final isSmallScreen = MediaQuery.of(context).size.width < 600;
          return Scaffold(
            key: _key,
            appBar: isSmallScreen
                ? AppBar(
                    backgroundColor: canvasColor,
                    title: Text(_getTitleByIndex(_controller.selectedIndex)),
                    leading: IconButton(
                      onPressed: () {
                        _key.currentState?.openDrawer();
                      },
                      icon: const Icon(Icons.menu),
                    ),
                  )
                : null,
            drawer: ExampleSidebarX(controller: _controller),
            body: Row(
              children: [
                if (!isSmallScreen) ExampleSidebarX(controller: _controller),
                Expanded(
                  child: Center(
                    child: _ScreensExample(
                      controller: _controller,
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

class ExampleSidebarX extends StatelessWidget {
  const ExampleSidebarX({
    Key? key,
    required SidebarXController controller,
  })  : _controller = controller,
        super(key: key);

  final SidebarXController _controller;

  @override
  Widget build(BuildContext context) {
    return SidebarX(
      controller: _controller,
      theme: SidebarXTheme(
        margin: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: canvasColor,
          borderRadius: BorderRadius.circular(20),
        ),
        hoverColor: scaffoldBackgroundColor,
        textStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
        selectedTextStyle: const TextStyle(color: Colors.white),
        hoverTextStyle: const TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.w500,
        ),
        itemTextPadding: const EdgeInsets.only(left: 30),
        selectedItemTextPadding: const EdgeInsets.only(left: 30),
        itemDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: canvasColor),
        ),
        selectedItemDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(
            color: actionColor.withOpacity(0.37),
          ),
          gradient: const LinearGradient(
            colors: [accentCanvasColor, canvasColor],
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.28),
              blurRadius: 30,
            )
          ],
        ),
        iconTheme: IconThemeData(
          color: Colors.white.withOpacity(0.7),
          size: 20,
        ),
        selectedIconTheme: const IconThemeData(
          color: Colors.white,
          size: 20,
        ),
      ),
      extendedTheme: const SidebarXTheme(
        width: 200,
        decoration: BoxDecoration(
          color: canvasColor,
        ),
      ),
      footerDivider: divider,
      headerBuilder: (context, extended) {
        return SizedBox(
          height: 100,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Image.asset('assets/images/avatar.png'),
          ),
        );
      },
      items: [
        SidebarXItem(
          icon: Icons.home,
          label: 'Home',
          onTap: () {
            debugPrint('Home');
          },
        ),
        const SidebarXItem(
          icon: Icons.search,
          label: 'Search',
        ),
        const SidebarXItem(
          icon: Icons.people,
          label: 'People',
        ),
        SidebarXItem(
          icon: Icons.favorite,
          label: 'Favorites',
          selectable: false,
          onTap: () => _showDisabledAlert(context),
        ),
        const SidebarXItem(
          iconWidget: FlutterLogo(size: 20),
          label: 'Flutter',
        ),
      ],
    );
  }

  void _showDisabledAlert(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Item disabled for selecting',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
      ),
    );
  }
}

class _ScreensExample extends StatelessWidget {
  const _ScreensExample({
    Key? key,
    required this.controller,
  }) : super(key: key);

  final SidebarXController controller;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        final pageTitle = _getTitleByIndex(controller.selectedIndex);
        switch (controller.selectedIndex) {
          case 0:
            return ListView.builder(
              padding: const EdgeInsets.only(top: 10),
              itemBuilder: (context, index) => Container(
                height: 100,
                width: double.infinity,
                margin: const EdgeInsets.only(bottom: 10, right: 10, left: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Theme.of(context).canvasColor,
                  boxShadow: const [BoxShadow()],
                ),
              ),
            );
          default:
            return Text(
              pageTitle,
              style: theme.textTheme.headlineSmall,
            );
        }
      },
    );
  }
}

String _getTitleByIndex(int index) {
  switch (index) {
    case 0:
      return 'Home';
    case 1:
      return 'Search';
    case 2:
      return 'People';
    case 3:
      return 'Favorites';
    case 4:
      return 'Custom iconWidget';
    case 5:
      return 'Profile';
    case 6:
      return 'Settings';
    default:
      return 'Not found page';
  }
}

const primaryColor = Color(0xFF685BFF);
const canvasColor = Color(0xFF2E2E48);
const scaffoldBackgroundColor = Color(0xFF464667);
const accentCanvasColor = Color(0xFF3E3E61);
const white = Colors.white;
final actionColor = const Color(0xFF5F5FA7).withOpacity(0.6);
final divider = Divider(color: white.withOpacity(0.3), height: 1);

这个示例展示了如何创建一个带有侧边栏的应用程序,并根据屏幕大小自动调整侧边栏的行为(如在小屏幕上作为抽屉)。希望这能帮助您更好地理解和使用sidebarx插件!


更多关于Flutter侧边栏导航插件sidebarx的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter侧边栏导航插件sidebarx的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用sidebar_menu(注意:sidebarx并不是一个广泛认可的插件名称,这里假设你指的是类似功能的侧边栏导航插件,如flutter_sidebar或自定义实现的一个侧边栏功能。为了演示,我将使用假设的侧边栏插件逻辑和代码案例)的示例。

示例:在Flutter中实现侧边栏导航

1. 添加依赖

首先,在你的pubspec.yaml文件中添加侧边栏导航相关的依赖。由于sidebarx不是官方或广泛认可的插件,这里我们假设使用flutter_sidebar或类似的插件(实际使用时请替换为实际存在的插件名)。

dependencies:
  flutter:
    sdk: flutter
  flutter_sidebar: ^x.y.z  # 替换为实际版本号

然后运行flutter pub get来获取依赖。

2. 创建侧边栏导航布局

在你的主页面(如main.dart)中,设置侧边栏导航布局。以下是一个基本的实现示例:

import 'package:flutter/material.dart';
import 'package:flutter_sidebar/flutter_sidebar.dart';  // 假设的包名

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Sidebar Navigation',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SidebarScaffold(
        menu: SidebarMenu(
          header: Text('Menu'),
          items: [
            SidebarMenuItem(
              title: 'Home',
              icon: Icons.home,
              onTap: () {
                Navigator.of(context).pushReplacementNamed('/home');
              },
            ),
            SidebarMenuItem(
              title: 'Settings',
              icon: Icons.settings,
              onTap: () {
                Navigator.of(context).pushReplacementNamed('/settings');
              },
            ),
            // 添加更多菜单项
          ],
        ),
        body: Navigator(
          initialRoute: '/home',
          onGenerateRoute: (RouteSettings settings) {
            Widget screen;
            switch (settings.name) {
              case '/home':
                screen = HomeScreen();
                break;
              case '/settings':
                screen = SettingsScreen();
                break;
              // 添加更多路由
              default:
                screen = Scaffold(
                  body: Center(
                    child: Text('No route defined for ${settings.name}'),
                  ),
                );
            }
            return MaterialPageRoute(builder: (context) => screen);
          },
        ),
      ),
    );
  }
}

class SidebarMenuItem extends StatelessWidget {
  final String title;
  final IconData icon;
  final VoidCallback onTap;

  SidebarMenuItem({required this.title, required this.icon, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Icon(icon),
      title: Text(title),
      onTap: onTap,
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: Center(
        child: Text('Home Screen'),
      ),
    );
  }
}

class SettingsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings'),
      ),
      body: Center(
        child: Text('Settings Screen'),
      ),
    );
  }
}

3. 运行应用

确保所有文件保存后,运行你的Flutter应用。你应该会看到一个带有侧边栏导航的主界面,点击侧边栏菜单项可以切换到不同的屏幕。

注意

  • 上面的代码是一个简化的示例,实际项目中可能需要根据需求进行调整。
  • 如果sidebarx是一个特定的、非公开的或新发布的插件,请查阅其官方文档或仓库以获取正确的使用方法。
  • flutter_sidebar是一个假设的包名,实际使用时请替换为实际存在的侧边栏导航插件。

希望这个示例能帮助你在Flutter项目中实现侧边栏导航功能!

回到顶部