I am relatively new to Flutter and I am trying to add the new Material 3 Search Bar to my app along with a Drawer navigation but it's not working as expected.
This is how it's appearing:
The navigation icon should've been inside the search bar.
Below is my code:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
clipBehavior: Clip.none,
title: SearchBar(),
),
drawer: Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Item 1'),
onTap: () {
// Update the state of the app.
// ...
},
),
ListTile(
title: const Text('Item 2'),
onTap: () {
// Update the state of the app.
// ...
},
),
],
),
),
body: CustomScrollView(
scrollDirection: Axis.vertical,
slivers: [
// MesAppBar(),
HomeScreen(),
],
),
);
}
}
First, you need to remove the hamburger icon from AppBar. You can do so by setting automaticallyImplyLeading to false, after that, you can put your desired IconButton inside the SearchBar widget by setting the leading property. To manage the open/close functionality of the drawer, you can assign a GlobalKey to the Scaffold and do something like : _scaffoldKey.currentState?.openDrawer() or closeDrawer().
Here is the working code:
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldkey, // GlobalKey
appBar: AppBar(
clipBehavior: Clip.none,
automaticallyImplyLeading: false,
title: SearchBar(
leading: IconButton(
onPressed: () {
_scaffoldkey.currentState?.openDrawer();
},
icon: const Icon(Icons.menu)),
),
),
drawer: Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Item 1'),
onTap: () {
// Update the state of the app.
// ...
},
),
ListTile(
title: const Text('Item 2'),
onTap: () {
// Update the state of the app.
// ...
},
),
],
),
),
body: CustomScrollView(
scrollDirection: Axis.vertical,
slivers: [
// MesAppBar(),
HomeScreen(),
],
),
);
}