flutter 快速实现侧边栏

首先我们写一个侧边栏工具类,示例如下:

Dart 复制代码
import 'package:flutter/material.dart';

class Sidebar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          UserAccountsDrawerHeader(
            accountName: Text("用户名"),
            accountEmail: Text("用户邮箱"),
            currentAccountPicture: CircleAvatar(
              backgroundColor: Colors.white,
              child: Text(
                "U",
                style: TextStyle(fontSize: 40.0, color: Colors.blue),
              ),
            ),
          ),
          ListTile(
            leading: Icon(Icons.home),
            title: Text('首页'),
            onTap: () {
              Navigator.pop(context); // 关闭侧边栏
              // 添加导航逻辑
            },
          ),
          ListTile(
            leading: Icon(Icons.settings),
            title: Text('设置'),
            onTap: () {
              Navigator.pop(context); // 关闭侧边栏
              // 添加导航逻辑
            },
          ),
          ListTile(
            leading: Icon(Icons.info),
            title: Text('关于'),
            onTap: () {
              Navigator.pop(context); // 关闭侧边栏
              // 添加导航逻辑
            },
          ),
        ],
      ),
    );
  }
}

然后我们在需要的地方引用这个侧边栏页面,示例如下

Dart 复制代码
Scaffold(
            appBar: AppBar(
              title: Text('侧边栏示例'), // 自定义标题
            ),
            drawer: Sidebar(), // 使用自定义的侧边栏
            body: Center(
              child: Text('主页内容'),
            ),
          ),

效果如下所示

如果想将一个类改写成侧边栏工具类,只需要用Drawer将整个页面进行包裹一下,然后在使用页面的Scaffold里面加上drawer这个标签引用这个类,然后将点击跳转这个类的方法改写成Scaffold.of(context).openDrawer();即可完成快速构建侧边栏。

相关推荐
九酒16 小时前
AI Agent 开发踩坑记:口播功能非得用 APP 原生实现吗?
前端·人工智能·agent
Jackson__16 小时前
做了一段时间的AI coding后,我终于搞清了 CLI 和 MCP 的区别
前端·agent·ai编程
IT_陈寒19 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户479492835691520 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔21 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6871 天前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen1 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding1 天前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693551 天前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill1 天前
curl命令学习笔记一
前端