No Scaffold widget found when use BottomSheet - flutter

I am just learning Flutter and got stuck on this error:
No Scaffold widget found.
Home widgets require a Scaffold widget ancestor.
The specific widget that could not find a Scaffold ancestor was: Home
The ancestors of this widget were
but as you can see from my code I do have a Scaffold and I played around adding it wherever I can but I didn't work for.
What can be the reason to what I've done or didn't notice there?
import 'package:firebase_redux_app/services/firebase.auth.dart';
import 'package:flutter/material.dart';
// import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_redux_app/services/firestore.dart';
import 'package:provider/provider.dart';
import 'package:firebase_redux_app/screens/home/brewList.dart';
import 'package:firebase_redux_app/models/brew.dart';
class Home extends StatelessWidget {
final AuthService _auth = AuthService();
#override
Widget build(BuildContext context) {
void _showSettingsPanel() {
showBottomSheet(
context: context,
builder: (context) {
return Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 60.0),
child: Text('bottom sheet'),
);
});
}
return StreamProvider<List<Brew>>.value(
value: DBFirestore().brews,
child: Scaffold(
backgroundColor: Colors.brown[50],
appBar: AppBar(
title: Text('Brew Crew'),
backgroundColor: Colors.brown[400],
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
onPressed: () async {
await _auth.signOut();
},
icon: Icon(Icons.person),
label: Text('Log Out')),
FlatButton.icon(
icon: Icon(Icons.settings),
label: Text('settings'),
onPressed: () => _showSettingsPanel(),
)
],
),
body: BrewList(),
),
);
}
}

This error is caused because of the scope of your _showSettingsPanel method
There are 2 things you can do
1.
Make the _showSettingsPanel a method in the Home class and allow it take the context as a parameter. Hence, wrap your settings FlatButton in a Builder and pass the context to the _showSettingsPanel method.
Like this
class Home extends StatelessWidget {
void _showSettingsPanel(context) {
showBottomSheet(
context: context,
builder: (context) {
return Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 60.0),
child: Text('bottom sheet'),
);
});
}
#override
Widget build(BuildContext context) {
return StreamProvider<List<Brew>>(
value: DBFireStore().brews
child: Scaffold(
backgroundColor: Colors.brown[50],
appBar: AppBar(
title: Text('Brew Crew'),
backgroundColor: Colors.brown[400],
elevation: 0.0,
actions: <Widget>[
FlatButton.icon(
onPressed: () async {
},
icon: Icon(Icons.person),
label: Text('Log Out')),
Builder(
builder: (context) {
return FlatButton.icon(
icon: Icon(Icons.settings),
label: Text('settings'),
onPressed: () => _showSettingsPanel(context),
);
}
)
],
),
body: BrewList(),
),
);
}
}
2.
Wrap the Home widget in a Scaffold wherever you use it, instead of using just Home
Like this
Scaffold(body: Home())

now this prb has different solutions. U gotta use sccafoldKey
final _scaffoldKey = GlobalKey<ScaffoldState>();
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
_scaffoldKey.currentState!.showBottomSheet(
(context) => const AddTaskScreen());
},
icon: const Icon(Icons.add))
],
),

Related

How to navigate to other screen from navigation drawer in flutter

i have tried in the following way but it is not working please tell me the solutions
import 'package:book_recommendation_app/about.dart';
import 'package:book_recommendation_app/home.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
void onTap(menuItem) {
switch (menuItem) {
case 'item1':
print('item1 clicked');
break;
case 'item2':
print('item2 clicked');
break;
case 'item3':
print('item3 clicked');
break;
}
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
var menuItems = <String>['item1', 'item2', 'item3'];
return MaterialApp(
title: 'Book Reccomendation Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: <Widget>[
PopupMenuButton<String>(
onSelected: onTap,
itemBuilder: (BuildContext context) {
return menuItems.map((String choice) {
return PopupMenuItem<String>(
child: Text(choice),
value: choice,
);
}).toList();
})
],
),
body: searchBar(),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Item 1'),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
title: const Text('About us'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AboutUs()),
);
Navigator.pop(context);
},
),
],
),
),
),
// home: const MyHomePage(title: 'Book Reccomendation Demo Home Page'),
);
}
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
var menuItems = <String>['item1', 'item2', 'item3'];
return MaterialApp(
title: 'Book Reccomendation Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: <Widget>[
PopupMenuButton<String>(
onSelected: onTap,
itemBuilder: (BuildContext context) {
return menuItems.map((String choice) {
return PopupMenuItem<String>(
child: Text(choice),
value: choice,
);
}).toList();
})
],
),
body: searchBar(),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Item 1'),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
title: const Text('About us'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AboutUs()),
);
Navigator.pop(context);
},
),
],
),
),
),
// home: const MyHomePage(title: 'Book Reccomendation Demo Home Page'),
);
}
}
Do not call Navigator.pop(context) immediately afther calling Navigator.push. Because for me it looks like your currently pushing to the next screen, but immediately popping again so that it will never be reached.
In this ListTile
ListTile(
title: const Text('About us'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AboutUs()),
);
Navigator.pop(context);
},
),
You use Navigator.Push(context,MaterialPageRout(builder: (context) => AboutUs()));
then you use Navegator.pop(context);
that means you push a new screen then you closed it and here is the problem
you need just to remove this line Navigator.pop(context);
You can use GetX too for navigate your pages in easier way if you don't want to go with MaterialPageRoute.
ListTile(
title: const Text('About us'),
onTap: () {
Get.to(AboutUs());
Navigator.pop(context);
},
),
Pop the drawer before pushing to new screen,
Like
Navigator.pop(context);
Navigator.push(context,
MaterialPageRoute(builder: (context) => AboutUs(),
),
);

How to display SnackBar in Flutter?

I want to display a SnackBar in my Flutter app. I have read the docs and copyed it:
The body of my scaffold:
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("Osztályok"),
leading: Padding(
padding: const EdgeInsets.only(left: 5.0),
child: IconButton(
icon: Icon(Icons.exit_to_app, color: Colors.white70),
onPressed: () {
authService.signOut();
authService.loggedIn = false;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GoogleSignUp()));
})),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 5.0),
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.add_circle_outline,
color: Colors.white70),
onPressed: () {
createPopup(context);
}),
// IconButton(
// icon: Icon(Icons.search, color: Colors.black38),
// onPressed: null),
],
)),
],
),
The SnackBarPage class:
class SnackBarPage extends StatelessWidget {
void jelszopress(TextEditingController jelszoController, BuildContext context) async{
var jelszo;
DocumentReference docRef =
Firestore.instance.collection('classrooms').document(globals.getid());
await docRef.get().then((value) => jelszo= (value.data['Jelszo']) );
if (jelszo == jelszoController.text.toString()){
Navigator.push(context,
MaterialPageRoute(builder: (context) => InClassRoom()));
}
else{
Navigator.pop(context);
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
Scaffold.of(context).showSnackBar(snackBar);
}
}
Future<String> jelszoba(BuildContext context) {
TextEditingController jelszoController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Add meg a jelszót'),
content: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: TextField(
controller: jelszoController,
decoration: InputDecoration(hintText: "Jelszó")
)
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('Mehet'),
onPressed: () {
jelszopress(jelszoController, context);
},
)]);
}
);
}
var nevek;
var IDS;
SnackBarPage(this.nevek, this.IDS);
#override
Widget build(BuildContext context){
return ListView.builder(
itemCount: nevek.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {
globals.setid(IDS[index]);
jelszoba(context);
},
title: Text(nevek[index]),
),
);
},
) ;
}
}
But my cody doesn't display the SnackBar. I tried the solution of this question: How to properly display a Snackbar in Flutter? but adding a Builder widget didn't help.
"Scaffold.of(context)" has been deprecated, will return null. Now use "ScaffoldMessenger.of(context)". As per Flutter documentation.
#override
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('snack'),
duration: const Duration(seconds: 1),
action: SnackBarAction(
label: 'ACTION',
onPressed: () { },
),
));
},
child: const Text('SHOW SNACK'),
),
),
);
}
NOTE: Make sure your main.dart overrided build() function should return "MaterialApp" as a widget, such as:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// Must be MaterialApp widget for ScaffoldMessenger support.
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyDashboard(),
);
}
}
So based on the error, it would seem that the context passed in Snackbar.of() is not the correct context. This would make sense based on 1 & 2; and summary copied below:
Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.build or State.build function. (And similarly, the parent of any children for RenderObjectWidgets.)
In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method.
So this means that the build context you are passing in jelszoba(context) function is not the build context you need and is actually the build context of the widget that is instantiating the Scaffold.
So How to Fix:
To fix this wrap your Card widget in your SnackbarPage in a Builder widget and pass the context from it, to the jelszoba(context) method.
An example from 1 I post below:
#override
Widget build(BuildContext context) {
// here, Scaffold.of(context) returns null
return Scaffold(
appBar: AppBar(title: Text('Demo')),
body: Builder(
builder: (BuildContext context) {
return FlatButton(
child: Text('BUTTON'),
onPressed: () {
// here, Scaffold.of(context) returns the locally created Scaffold
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('Hello.')
));
}
);
}
)
);
}
You can normally use snack bar in the Bottom Navigation bar in this way. However, if you want to show it in the body, then just copy the code from Builder and paste it in the body of the scaffold.
Scaffold(bottomNavigationBar: Builder(builder: (context) => Container(child: Row(children: <Widget>[
Icon(Icons.add_alarm), Icon(Icons.map), IconButton(icon: Icon(Icons.bookmark),
onPressed:() {
Scaffold.of(context).showSnackBar(mySnackBar);
final mySnackBar = SnackBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, duration: Duration(seconds: 1),
content: Text(
'Article has been removed from bookmarks',
),);
}
),
],
),
),
),
);
Note: In the behaviour property of SnackBar, you can just leave it empty. But the problem with that is "If you have Curved Navigation Bar or you have a floating action button above the bottom navigation bar, then the snackbar will lift these icons (or FAB ) and will affect the UI". That's why SnackBar.floating is more preferred as it is more capatible with the UI.
But you can check and see on your own which suits you the best.

How can I change Drawer icon in flutter?

The drawer has this default three horizontal bars as default icon but I want to change it to something else.
I have checked the possible options under the Drawer(), but no property seems to be attached to that.
This should work.
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text('hi'),
leading: IconButton(
icon: Icon(Icons.accessible),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
);
From the docs ->
{Widget leading} Type: Widget
A widget to display before the [title].
If this is null and [automaticallyImplyLeading] is set to true, the [AppBar] will imply an appropriate widget. For example, if the [AppBar] is in a [Scaffold] that also has a [Drawer], the [Scaffold] will fill this widget with an [IconButton] that opens the drawer (using [Icons.menu]). If there's no [Drawer] and the parent [Navigator] can go back, the [AppBar] will use a [BackButton] that calls [Navigator.maybePop].
The following code shows how the drawer button could be manually specified instead of relying on [automaticallyImplyLeading]:
import 'package:flutter/material.dart';
Widget build(context) {
return AppBar(
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openDrawer();
},
tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
);
},
),
);
}
The [Builder] is used in this example to ensure that the context refers to that part of the subtree. That way this code snippet can be used even inside the very code that is creating the [Scaffold] (in which case, without the [Builder], the context wouldn't be able to see the [Scaffold], since it would refer to an ancestor of that widget).
appBar: AppBar(
leading: Builder(
builder: (context) => IconButton(
icon: Icon(Icons.menu_rounded),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
title: Text(
"Track your Shipment",
),
),
You can open a drawer with a custom button like this too.
create this scaffold key.
var scaffoldKey = GlobalKey<ScaffoldState>();
now added a scaffolled in your state class like this
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
drawer: Drawer(
child: Text('create drawer widget tree here'),
),
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
'appName',
style: Theme.of(context).textTheme.headline2,
),
leading: IconButton(
onPressed: () {
scaffoldKey.currentState?.openDrawer();
},
icon: Image.asset(
'assets/images/menu.png',
fit: BoxFit.cover,
),
),
),
body: Container(),
);
}
Lets say you have: index.dart (where you want to use the appbar), drawer.dart (your drawer or navigation menu) and appbar.dart (your appbar)
you can do this in drawer:
Widget drawer(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Container(
...
)
);
then your appbar.dart:
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
#override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.white,
leading: InkWell(
onTap: () => Scaffold.of(context).openDrawer(),
child: Image.asset("assets/images/imgAppBar.png"),
),
title: Container(...
then your index.dart:
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
drawer: drawer(context),
appBar: CustomAppBar(),
...
this is just a simple one. You can use IconButton in case you want to use an Icon etc.
You need to create the Global key of type ScaffoldKey the use that to open the drawer and change the icon too:
Widget build(BuildContext context) {
var scaffoldKey = GlobalKey<ScaffoldState>();
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title:Text('hi'),
leading: IconButton(
icon: Icon(Icons.accessible),
onPressed: () => scafoldKey.currentState.openDrawer(),
),
),
);
Actually, i tried the answer by cmd_prompter and it didn't work for me.
The better approach is described here
My working code is here:
return DefaultTabController(
key: Key("homePage"),
length: 2,
child: Scaffold(
endDrawer: Drawer(
),
appBar: AppBar(
leading: BackButton(
onPressed: () {
},
),
title: Text(profile.selectedCity!),
actions: [
Padding(
padding: EdgeInsets.symmetric(horizontal: baseUnit(3)),
child: Builder(
builder: (context) => IconButton(
icon: Icon(Icons.account_circle),
onPressed: () => Scaffold.of(context).openEndDrawer(),
)
)
)
It worked fine for me - especially this part regarding using Builder. This is important - otherwise it was not working for me.
class HomeOne extends StatefulWidget { const HomeOne({Key? key}) : super(key: key);
#override State createState() =>HomeOneState(); }
var scaffoldKey = GlobalKey();
class HomeOneState extends State { #override Widget build(BuildContext context) { var theme = Theme.of(context); return Directionality( textDirection: TextDirection.rtl, child: Scaffold( key: scaffoldKey, drawerEnableOpenDragGesture: true, // drawerScrimColor: Colors.red, appBar: AppBar( leading: IconButton( onPressed: () => scaffoldKey.currentState?.openDrawer(), icon: const Icon( Icons.add, color: Colors.red, )), ),
AppBar(
leading: IconButton(
onPressed: () {
// Code
},
icon: Icon(Icons.arrow_back),
),
),
To only change the icon color, it's easier to do by adding an iconTheme to the AppBar:
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(
title: Text("Navigation Drawer"),
iconTheme: IconThemeData(color: Colors.green),
),
);
}

Flutter: How to open Drawer programmatically

I want to open Drawer programmatically not by sliding it, how to disable that sliding functionality (touch functionality of Drawer)
Null safe code
Using GlobalKey:
final GlobalKey<ScaffoldState> _key = GlobalKey(); // Create a key
#override
Widget build(BuildContext context) {
return Scaffold(
key: _key, // Assign the key to Scaffold.
drawer: Drawer(),
floatingActionButton: FloatingActionButton(
onPressed: () => _key.currentState!.openDrawer(), // <-- Opens drawer
),
);
}
Using Builder:
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
floatingActionButton: Builder(builder: (context) {
return FloatingActionButton(
onPressed: () => Scaffold.of(context).openDrawer(), // <-- Opens drawer.
);
}),
);
}
If you want to disable opening the Drawer using a drag gesture, you can set
Scaffold(
drawerEnableOpenDragGesture: false
// above code ...
)
To disable the slide to open functionality you can set the property drawerEnableOpenDragGesture on Scaffold to false.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
// this to prevent the default sliding behaviour
drawerEnableOpenDragGesture: false,
drawer: Drawer(),
appBar: AppBar(
leading: Builder(builder: (context) => // Ensure Scaffold is in context
IconButton(
icon: Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer()
),
),
)
)
);
}
}
To open the drawer programmatically using Scaffold.of(context) you'll have to ensure (thanks Krolaw !) that the context inside which the call is made is aware of the Scaffold.
A clean way to do it is to wrap the button in a builder.
I've edited the answer to include a minimal full working example.
Scaffold is a widget that implements material design principles, so be aware that to be able to call this method, you'll need to import 'package:flutter/material.dart'; and your widget needs to have a MaterialApp as ancestor.
Codepen demo
As with many Flutter things, there are other solutions to ensure Scaffold is in context.
Error messages are IMO among the best features of flutter framework, allow me to humbly suggest to always read them thoroughly and to explore the documentation they point at.
For instance, this is part of the error message that one gets if calling openDrawer outside of a proper context:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
https://api.flutter.dev/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
Calling Scaffold.of doesn't work because the context doesn't contain the Scaffold. Some solutions above have ignored this, others have used GlobalKey. I believe the cleanest solution is wrapping the button in a Builder:
Scaffold(
drawerEnableOpenDragGesture: false, // Prevent user sliding open
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text("Some Title"),
actions: [
Builder(builder: (context) => // Ensure Scaffold is in context
IconButton(
icon: Icon(Icons.settings),
onPressed: () => Scaffold.of(context).openDrawer()
)),
],
),
// TODO ...
)
Here is another example of opening the drawer programmatically from a hamburger icon and without the Appbar:-
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
var scaffoldKey = GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
key: scaffoldKey,
drawer: new Drawer(
child: new ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Item 1'),
onTap: () {
//Do some stuff here
//Closing programmatically - very less practical use
scaffoldKey.currentState.openEndDrawer();
},
)
],
),
),
body: Stack(
children: <Widget>[
new Center(
child: new Column(
children: <Widget>[],
)),
Positioned(
left: 10,
top: 20,
child: IconButton(
icon: Icon(Icons.menu),
onPressed: () => scaffoldKey.currentState.openDrawer(),
),
),
],
),
),
);
}
}
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(
"Infilon Technologies",
style:
TextStyle(fontFamily: "Poppins", fontWeight: FontWeight.w600),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.menu),
onPressed: () {
if (_scaffoldKey.currentState.isEndDrawerOpen) {
_scaffoldKey.currentState.openDrawer();
} else {
_scaffoldKey.currentState.openEndDrawer();
}
},
),
],
),
If you are using endDrawer (right to left) in Scaffold, you should use:
Scaffold.of(context).openEndDrawer();
If you are using drawer (left to right) in Scaffold, you should use:
Scaffold.of(context).openDrawer();
You can use this perfect method to open drawer
its Worked with null safty module above flutter 2.12
class DashBoardScreen extends StatefulWidget {
final String? screen;
const DashBoardScreen(this.screen, {super.key});
#override
State<DashBoardScreen> createState() => _DashBoardScreenState();
}
class _DashBoardScreenState extends State<DashBoardScreen> {
DashBoardScreenController controller =
Get.put(getIt<DashBoardScreenController>());
#override
Widget build(BuildContext context) {
controller.scaffoldKey = GlobalKey<ScaffoldState>();
return Obx(() => Scaffold(
key: controller.scaffoldKey,
onDrawerChanged: (isOpened) {
if (!isOpened) {
setState(() {});
}
},
appBar: AppBar(
title: const Text("Test drawer App"),
actions: const [
const Padding(
padding: EdgeInsets.only(right: 20),
child: Icon(Icons.search))
],
leading: UnconstrainedBox(
child: GestureDetector(
onTap: () {
controller.scaffoldKey.currentState!.openDrawer();
},
child: const AbsorbPointer(
absorbing: true,
child: SizedBox(
height: 50,
child: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(
"https://cdn.pixabay.com/photo/2014/07/09/10/04/man-388104_960_720.jpg",
)),
),
),
),
),
),
drawerEdgeDragWidth:
kIsWeb ? MediaQuery.of(context).size.width * 0.2 : null,
drawer: Drawer(
key: controller.scaffoldKey,
child: ListView(
children: [
DropdownMenuItem(onTap: () {}, child: const Text("Add Anime"))
],
)),
body: widget.screen == StringVariables.ADD_ANIME
? AddAnimeFragment(widget.screen!)
: Container(),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Add Anime',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Favourite',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
currentIndex: controller.bottomSheetIndex.value,
selectedItemColor: ColorName.primaryColor,
onTap: (s) {
controller.bottomSheetIndex.value = s;
},
),
));
}
}
Simply flow these steps
create a variable in class like this
var scaffoldKey = GlobalKey<ScaffoldState>();
then use this key in your scaffold like this
Scaffold(
key: scaffoldKey,
appBar: AppBar(
automaticallyImplyLeading: false,
leading: IconButton(
onPressed: () {
scaffoldKey.currentState?.openDrawer();
},
icon: Icon(
Icons.menu,
color: ExtraColors.PRIMARY_800,
)),
title: Text(
'${AppStrings.appName}',
),
centerTitle: true,
),
)

Show back button instead of drawer button - flutter

I have a Flutter project which uses material design, that as I go through routes the appbar will show the backbutton. Recently, I just implemented a drawer in my project, and the drawer icon overrides the back icon. I essentially want to undo this, showing the back button, for certain screens, and show the menu button for other screens, almost like when I define the drawer having a showIcon: false property? I understand this post is a similar question, but no code is shown for the question or the solution... My drawer looks like this:
return Scaffold(
//appbar is here
appBar: AppBar(
title: Text("Title"),
),
drawer: drawer,
body: _buildBody(),
);
And I define drawer here:
var drawer = Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
//My listTiles and UserAccountsDrawerHeader are removed for simplicity
],
),
);
Thanks for any help.
Short answer:
AppBar(
leading: IconButton(
onPressed: () {}, // Handle your on tap here.
icon: Icon(Icons.arrow_back_ios),
),
)
Screenshot:
Full code:
void main() => runApp(MaterialApp(home: MyPage()));
class MyPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
ElevatedButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => Page1())),
child: Text("Go to Drawer Page"),
),
ElevatedButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => Page2())),
child: Text("Go to Back button Page"),
),
],
),
),
);
}
}
// This has drawer
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
drawer: Drawer(),
);
}
}
// This has back button and drawer
class Page2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context),
),
),
drawer: Drawer(),
);
}
}
AppBar(
leading: Builder(
builder: (BuildContext context) {
return IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () { Navigator.pop(context); },
);
},
),
)