Navigation issues with Flutter - flutter

I am currently having issues navigating from one page to another on my flutter application. I am really new to Flutter, as this is my first application, and this site has helped me before so I'm hoping it will help me again.
The code below in the "//Drawer List" section is having issues with the "Navigator.push" within "onTap" which I want to implement for multiple ListTiles. The code runs great in my Android Emulator, but when I click the ListTile in the drawer I get this in the terminal:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a
descendant of a Navigator widget.
When the exception was thrown, this was the stack:
#0 Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2553:9)
#1 Navigator.of (package:flutter/src/widgets/navigator.dart:2560:6)
#2 Navigator.push (package:flutter/src/widgets/navigator.dart:2016:22)
#3 MyApp.build.<anonymous closure> (package:bit/main.dart:58:27)
#4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:989:21)
#5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:608:11)
#7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
#8 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7)
#9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
#10 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:443:20)
#11 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#12 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#13 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#14 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#15 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#16 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#20 _invoke1 (dart:ui/hooks.dart:170:10)
#21 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
#22 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
(elided 3 frames from dart:async)
Handler: "onTap"
Recognizer:
TapGestureRecognizer#d5f04
════════════════════════════════════════════════════════════════════════════════════════════════════
After clicking it a second time a second error comes up and then repeats.
Another exception was thrown: Navigator operation requested with a context that does not include a
Navigator.
I tried messing with a few solutions I found online, but all of them seemed to give me the same error so I was hoping someone could help me fix/find what I am missing in the below code. Thank you.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: MyApp(),
));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var scaffold = Scaffold(
appBar: AppBar(
title: const Text('Test App'),
),
// Body Home Page Beginning
body: SingleChildScrollView(
child: Container(
child: const Center(
child: Text('Hello'),
))),
// Body Home Page End
drawer: Drawer(
// Drawer Beginning
child: ListView(
children: [
// Drawer Header
DrawerHeader(
decoration: const BoxDecoration(
color: Colors.blue,
),
child: Stack(
children: const [
Align(
alignment: Alignment.centerLeft,
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 50.0,
)),
Align(
alignment: Alignment.centerRight,
child: Text(
'Username',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
))
],
),
),
// Drawer List
ListTile(
title: const Text('Profile'),
subtitle: const Text('Account Information'),
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => const About()),
);
},
trailing: const Icon(Icons.arrow_forward_ios_rounded),
),
const ListTile(
title: Text('Education'),
subtitle: Text('Homeschool Education Material & Quizzes'),
trailing: Icon(Icons.arrow_forward_ios_rounded),
),
const ListTile(),
],
),
),
// Drawer End
);
return MaterialApp(
title: 'Test App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: scaffold,
);
}
}
class About extends StatelessWidget {
const About({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
}
class SinTracker extends StatelessWidget {
const SinTracker({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
}
All code is stored in "main.dart" file.

VS Code and my emulator just needed a reboot/restart. Someone checked it in the comments and I am simply providing an anwser to get it off the questions list.

Related

How can I fix exception "Floating SnackBar presented off screen" in flutter

I have an app that displays a snackbar when some action is done. I had tested this with my phone and some emulator and it works. Recently I installed an emulator with android 13 and maybe a bigger resolution and I'm getting this error:
The following assertion was thrown during performLayout():
Floating SnackBar presented off screen.
A SnackBar with behavior property set to SnackBarBehavior.floating is fully or partially off screen because some or all the widgets provided to Scaffold.floatingActionButton, Scaffold.persistentFooterButtons and Scaffold.bottomNavigationBar take up too much vertical space.
Consider constraining the size of these widgets to allow room for the SnackBar to be visible.
The relevant error-causing widget was
Scaffold
dashboard.dart:69
When the exception was thrown, this was the stack
#0 _ScaffoldLayout.performLayout.<anonymous closure>
#0 _ScaffoldLayout.performLayout.<anonymous closure>
scaffold.dart:1189
#1 _ScaffoldLayout.performLayout
scaffold.dart:1204
#2 MultiChildLayoutDelegate._callPerformLayout
custom_layout.dart:240
#3 RenderCustomMultiChildLayoutBox.performLayout
custom_layout.dart:410
#4 RenderObject._layoutWithoutResize
object.dart:2027
#5 PipelineOwner.flushLayout
object.dart:1020
#6 RendererBinding.drawFrame
binding.dart:516
#7 WidgetsBinding.drawFrame
binding.dart:865
#8 RendererBinding._handlePersistentFrameCallback
binding.dart:381
#9 SchedulerBinding._invokeFrameCallback
binding.dart:1289
#10 SchedulerBinding.handleDrawFrame
binding.dart:1218
#11 SchedulerBinding._handleDrawFrame
binding.dart:1076
#12 _invoke (dart:ui/hooks.dart:145:13)
#13 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:338:5)
#14 _drawFrame (dart:ui/hooks.dart:112:31)
The following RenderObject was being processed when the exception was fired: RenderCustomMultiChildLayoutBox#3f6d8 NEEDS-LAYOUT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: RenderCustomMultiChildLayoutBox#3f6d8 NEEDS-LAYOUT NEEDS-COMPOSITING-BITS-UPDATE
needs compositing
parentData: <none> (can use size)
constraints: BoxConstraints(w=411.4, h=867.4)
size: Size(411.4, 867.4)
child 1: RenderRepaintBoundary#ba78b relayoutBoundary=up1
needs compositing
I have no idea how can I debug what is going on here. The code works in smaller devices/older versions of android. The popups are triggered quiet straightforward:
SnackBar getSnackbar({
required String message,
required Color backgroundColor,
}) {
return SnackBar(
elevation: 8,
backgroundColor: backgroundColor,
behavior: SnackBarBehavior.floating,
content: Row(children: [
Flexible(
child: Text(
message,
style: const TextStyle(
color: Colors.white,
),
),
)
]),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
);
}
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(getSnackbar(
backgroundColor: Colors.green,
message: 'File saved to $filename',
));
The screen where this is called does not have any Scaffold.floatingActionButton, Scaffold.persistentFooterButtons and Scaffold.bottomNavigationBar as the exception says. It is just a Scaffold with a body:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SomeScreen'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: _isLoading
? const Center(child: CircularProgressIndicator())
: Column(children: [
_displaySomething(),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
_displayAnotherThing(),
],
))
]),
),
);
}
Update: I have futher debugged the issue and it also happens in older versions of android. So it may be related to a recent update of flutter but I'm not able to find why.
I was able to see the problem appears only with behavior:SnackBarBehavior.floating,.
Also removing all the code from the Scaffolfd, leaving just the TextButton that triggers the snackbar is enough to reproduce the issue, but I don't know what can I do with it.
I faced this problem too. This problem arises due to the fact that your column takes up all the available space, you need to limit it somehow to give room for a snackbar
I cross posted this here, because I though it was a bug. But there it was explained that for the SnackBars you have to also consider other Scaffolds in the widget tree as moving backwards would keep the snackbar "flying" and could collide with elements of the previous Scaffolds.
So as a summary on how to solve this issue, take a look not only in the screen where you see the exception triggered but also from previous screens.

Scaffold.geometryOf() must only be accessed during the paint phase

Exception is thrown when debugging on windows, stacktrace:
ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Scaffold.geometryOf() must only be accessed during the paint phase.
The ScaffoldGeometry is only available during the paint phase, because its value is computed during the animation and layout phases prior to painting.
#0 _ScaffoldGeometryNotifier.value.<anonymous closure> (package:flutter/src/material/scaffold.dart:835:9)
#1 _ScaffoldGeometryNotifier.value (package:flutter/src/material/scaffold.dart:842:6)
#2 _BottomAppBarClipper.getClip (package:flutter/src/material/bottom_app_bar.dart:238:35)
The stacktrace is hinting at getting geometry values from a BottomAppBar which is what I have in my widget. This error is followed by a lot of error messages for mouse_tracker when I move the mouse on the screen:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 'package:flutter/src/rendering/mouse_tracker.dart': Failed assertion: line 195 pos 12: '!_debugDuringDeviceUpdate': is not true.
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:40:5)
#2 MouseTracker._deviceUpdatePhase (package:flutter/src/rendering/mouse_tracker.dart:195:12)
Nothing on the screen is clickable after this.
The error occurs only after the FloatingActionButton is pressed, and not if the back button on the page is pressed. The onPressed for the FAB is:
void onOkPressed() {
Navigator.of(context).pop();
}
How can I solve this error?
The FAB is contained in the bottom app bar, try setting the FAB location to float
from
Scaffold(
appBar: const AppBar(),
bottomNavigationBar: const BottomAppBar(),
floatingActionButton: FloatingActionButton(
onPressed: onOkPressed,
child: const Icon(Icons.check, size: 32),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endContained,
....
to
Scaffold(
appBar: const AppBar(),
bottomNavigationBar: const BottomAppBar(),
floatingActionButton: FloatingActionButton(
onPressed: onOkPressed,
child: const Icon(Icons.check, size: 32),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
....

No TabController for TabBar when adding bottom TabBar to AppBar (Flutter)

So what I'm trying to do, besides my app bar where I have logo and search option I want to add bottom TabBar where user can choose between movies or tv shows, and while he is on one of them the text should be lit up (different color). But when I tried to add the TabBar i got an error:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building MediaQuery(MediaQueryData(size: Size(411.4, 683.4),
devicePixelRatio: 2.6, textScaleFactor: 1.0, platformBrightness: Brightness.light, padding:
EdgeInsets.zero, viewPadding: EdgeInsets.zero, viewInsets: EdgeInsets.zero, alwaysUse24HourFormat:
false, accessibleNavigation: false, highContrast: false, disableAnimations: false, invertColors:
false, boldText: false, navigationMode: traditional)):
No TabController for TabBar.
When creating a TabBar, you must either provide an explicit TabController using the "controller"
property, or you must ensure that there is a DefaultTabController above the TabBar.
In this case, there was neither an explicit controller nor a default controller.
The relevant error-causing widget was:
AppBar file:///C:/Users/Meliha/Desktop/Rubicon/chillax/lib/presenter/home_page_movies.dart:22:15
When the exception was thrown, this was the stack:
#0 _TabBarState._updateTabController.<anonymous closure> (package:flutter/src/material/tabs.dart:965:9)
#1 _TabBarState._updateTabController (package:flutter/src/material/tabs.dart:974:6)
#2 _TabBarState.didChangeDependencies (package:flutter/src/material/tabs.dart:1006:5)
#3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4653:11)
#4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4469:5)
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#6 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6094:32)
... Normal element mounting (99 frames)
#105 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#106 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6094:32)
... Normal element mounting (238 frames)
#344 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#345 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6094:32)
... Normal element mounting (300 frames)
#645 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3541:14)
#646 Element.updateChild (package:flutter/src/widgets/framework.dart:3306:18)
#647 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1182:16)
#648 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1153:5)
#649 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1095:18)
#650 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2647:19)
#651 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1094:13)
#652 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:934:7)
#653 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:915:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
Here is the code of the main page for the movies:
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:movie_app/view/now_playing_movie.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:movie_app/view/now_playing_tv.dart';
import 'package:movie_app/view/test.dart';
import 'package:movie_app/view/top_movies.dart';
import 'package:movie_app/view/top_tvs.dart';
import '../style/style.dart';
class HomePageMovie extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePageMovie> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFF151C26),
appBar: AppBar(
backgroundColor: Color(0xFF151C26),
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SvgPicture.asset(
logo,
height: 195,
),
],
),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: Icon(
EvaIcons.searchOutline,
color: Colors.white,
))
],
bottom: TabBar(
indicatorColor: Color(0xFFf4C10F),
indicatorSize: TabBarIndicatorSize.tab,
indicatorWeight: 3.0,
unselectedLabelColor: Colors.white,
labelColor: Colors.white,
isScrollable: true,
tabs: [
Tab(
icon: Icon(Icons.movie),
text: "Movies",
),
Tab(
icon: Icon(Icons.tv),
text: "TV Shows",
)
]),
titleSpacing: 0.0,
),
body: ListView(
children: <Widget>[
NowPlayingMovies(),
BestMovie(),
],
),
);
}
}
Any form of help/tip/guide would be great. Thanks in advance
The solution for your problem is right inside the error text
When creating a TabBar, you must either provide an explicit TabController using the "controller"
property, or you must ensure that there is a DefaultTabController above the TabBar.
Therefore the easiest solution is to wrap your TabBar with the DefaultTabController. Since you are making use of the bottom property of AppBar which expects a PreferredSizeWidget, you additionally need to wrap it all inside something that implements this (since it's an abstract class) - easiest solution here is to just make use of PreferredSize. Complete example could look like this:
AppBar(
bottom: PreferredSize(
// Set whatever size you want - this is a good default one
preferredSize: Size.fromHeight(kToolbarHeight),
child: DefaultTabController(
length: 2,
child: TabBar(
tabs: [
Tab(
text: 'Movies',
),
Tab(
text: 'TV Shows',
),
],
),
),
),
),
The error logs are pretty verbose at times, but this is the crucial message:
When creating a TabBar, you must either provide an explicit TabController using the "controller"
property, or you must ensure that there is a DefaultTabController above the TabBar.
In this case, there was neither an explicit controller nor a default controller.
You just need to wrap your Scaffold widget in a DefaultTabController and give it a length corresponding to the number of tabs you have. For more complex behaviour you can initialise a ScrollController and add this to the controller: parameter of the TabBar and TabBarView.
I also notice in the example you have a ListView containing your two tab widgets. This won't work, swap it out for a TabBarView.

Flutter app crashes when returning to previous screen

I have a Flutter app that populates a list of river gauge information and allows the user to select an item and view details in a chart, using the charts_flutter package.
I have used the chart successfully in the past with a FutureBuilder, and now it is being refactored to use a Provider. The view containing the chart works as expected, but when returning to the previous screen (the list of gauges) I receive an error after the list shows very briefly. The error is as follows.
This is the code that renders the chart view
class GaugeDetailChart extends StatefulWidget {
GaugeReferenceModel referenceModel;
GaugeDetailChart({this.referenceModel});
#override
_GaugeDetailChartState createState() => _GaugeDetailChartState();
}
class _GaugeDetailChartState extends State<GaugeDetailChart> {
GaugeDetailViewModel viewModel;
#override
void initState() {
_loadData();
super.initState();
}
_loadData() {
viewModel = Provider.of<GaugeDetailViewModel>(context, listen: false);
viewModel.reloading = true;
viewModel.setReferenceModel(widget.referenceModel);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: RLAppBar(
titleText: Text('Gauge Detail'),
),
body: Center(
child: Consumer<GaugeDetailViewModel>(
builder: (context, model, child) => Stack(
children: [
Center(
child: Visibility(
visible: model.reloading,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Loading details for'),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('${widget.referenceModel.gaugeName}'),
)
],
)),
),
// removing the following container resolves the exception
Container(
height: MediaQuery.of(context).size.height * .5,
alignment: Alignment(0.0, 0.0),
color: Colors.lightBlueAccent,
child: charts.TimeSeriesChart(
model.seriesFlowData,
animate: true,
animationDuration: Duration(milliseconds: 500),
primaryMeasureAxis: charts.NumericAxisSpec(
tickProviderSpec: charts.BasicNumericTickProviderSpec(
zeroBound: false,
dataIsInWholeNumbers: false,
desiredMaxTickCount: 8,
desiredMinTickCount: 5),
renderSpec: charts.GridlineRendererSpec(
tickLengthPx: 0, labelOffsetFromAxisPx: 5)),
)
)
],
),
),
));
}
}
The chart renders on the view correctly. The only time the error occurs is when exiting this view and returning to the previous view, which is performed using the NavigationController back button.
If I remove the Container that holds the chart, then returning to the previous view works without error. Something about the Container is causing the previous view to fail. The errors generated are very vague.
The following assertion was thrown building Overlay-[LabeledGlobalKey<OverlayState>#5f9d5](state: OverlayState#a6169(entries: [OverlayEntry#2b4ce(opaque: true; maintainState: false), OverlayEntry#eea3d(opaque: false; maintainState: true), OverlayEntry#c217d(opaque: true; maintainState: false), OverlayEntry#ae45e(opaque: false; maintainState: true), OverlayEntry#c7b73(opaque: true; maintainState: false), OverlayEntry#e34a6(opaque: false; maintainState: true)])):
'package:flutter/src/widgets/framework.dart': Failed assertion: line 5125 pos 14: '_dependents.isEmpty': is not true.
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=BUG.md
The relevant error-causing widget was:
MaterialApp file:///Users/philiptownsend/Documents/projects.nosync/_Flutter/RiverLink/stream_watcher/lib/main.dart:32:12
When the exception was thrown, this was the stack:
#2 InheritedElement.debugDeactivated.<anonymous closure> (package:flutter/src/widgets/framework.dart:5125:14)
#3 InheritedElement.debugDeactivated (package:flutter/src/widgets/framework.dart:5127:6)
#4 _InactiveElements._deactivateRecursively.<anonymous closure> (package:flutter/src/widgets/framework.dart:2048:15)
#5 _InactiveElements._deactivateRecursively (package:flutter/src/widgets/framework.dart:2050:6)
#6 ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:4710:14)
Has anyone experienced anything like this before or can anyone make a recommendation on where to start looking or how to solve this?
Thanks!
I am not really sure but why don't you try making the container a seperate widget and try
calling that widget. Maybe that resolves the issue

showBottomSheet throwing an error complaining no scaffold

Redirecting from LoginPage to OnBoarding. While onboarding click on a button need to show the bottom sheet. Using the Named routes for navigation.
Later in the Loginpage will be navigating to the onboarding using Navigator.pushNamed(context, '/onboarding'); to redirect.
here is the main.dart
void main() {
runApp(
MultiProvider(
providers: [ChangeNotifierProvider(create: (context) => ThemeModel())],
child: DevicePreview(
enabled: !kReleaseMode,
builder: (context) => MyApp(),
),
),
);
SystemChrome.setEnabledSystemUIOverlays([]);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
locale: DevicePreview.of(context).locale, // <--- Add the locale
builder: DevicePreview.appBuilder, // <--- Add the builder
theme: Provider.of<ThemeModel>(context).currentTheme,
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => LoginPage(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/onboarding': (context) => OnboardingPage(),
'/home': (context) => Home(),
},
);
}
}
here is the code snippet for the buttonClick and then open the bottomsheet
_getButton(String hint, int index, BuildContext context) {
return MaterialButton(
height: 58,
minWidth: 340,
shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(12)),
onPressed: () {
if(index == 1){
**showBottomSheet(
context: context,
builder: (context) => BasicProfileBottomSheetWidget());
}**
},
child: Text(
hint,
style: TextStyle(
fontSize: 22,
color: Colors.black,
),
),
color: Colors.white,
);
}
Here is my widget tree
Here is the error.
[38;5;248m════════ Exception caught by gesture ═══════════════════════════════════════════[39;49m
[38;5;244mThe following assertion was thrown while handling a gesture:[39;49m
No Scaffold widget found.
[38;5;244mOnboardingPage widgets require a Scaffold widget ancestor.[39;49m
[38;5;244mThe specific widget that could not find a Scaffold ancestor was: OnboardingPage[39;49m
[38;5;244mstate: _OnboardingPageState#4c2bb[39;49m
[38;5;244mThe ancestors of this widget were[39;49m
[38;5;244mMaterialApp[39;49m
[38;5;244mstate: _MaterialAppState#e362b[39;49m
[38;5;244mMyApp[39;49m
[38;5;244mdependencies: [_InheritedProviderScope<ThemeModel>][39;49m
[38;5;244mDevicePreview[39;49m
[38;5;244mstate: DevicePreviewState#2a192[39;49m
[38;5;244mChangeNotifierProvider<ThemeModel>[39;49m
[38;5;244mvalue: Instance of 'ThemeModel'[39;49m
[38;5;244mlistening to value[39;49m
[38;5;244mMultiProvider[39;49m
[38;5;244m...[39;49m
[38;5;248mTypically, the Scaffold widget is introduced by the MaterialApp or WidgetsApp widget at the top of your application widget tree.[39;49m
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0 debugCheckHasScaffold.<anonymous closure>[39;49m
[38;5;244m#1 debugCheckHasScaffold[39;49m
[38;5;244m#2 showBottomSheet[39;49m
[38;5;248m#3 _getButton.<anonymous closure>[39;49m
[38;5;244m#4 _InkResponseState._handleTap[39;49m
[38;5;244m...[39;49m
[38;5;244mHandler: "onTap"[39;49m
[38;5;244mRecognizer: TapGestureRecognizer#bb0ca[39;49m
[38;5;244mdebugOwner: GestureDetector[39;49m
[38;5;244mstate: ready[39;49m
[38;5;244mwon arena[39;49m
[38;5;244mfinalPosition: Offset(422.5, 960.5)[39;49m
[38;5;244mfinalLocalPosition: Offset(166.7, 29.3)[39;49m
[38;5;244mbutton: 1[39;49m
[38;5;244msent tap down[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m
Try putting the Scaffold widget immediately after the MaterialApp, then OnBoardingPage can be inside the body of the Scaffold
Also, without using globalkey workaround below code worked..No clue on what is the actual root cause and fix though :)
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: MediaQuery.of(context).size.height * 0.50,
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(25.0),
topRight: const Radius.circular(25.0),
),
),
child: Center(
child: Text("Modal content goes here"),
),
),
);