How navigate to another screen - android

I have a next RaisedButton to go a next screen called DetailOracion.
Based on the example of Flutter to push new screen but doest work.
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Oraciones Cristianas'),
),
body: SafeArea(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailOracion()));
},
child: Text('Hello Wolrd'),
)
],
),
)),
),
);
}
My DetailOracion
class DetailOracion extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Hola'),
),
body: Text('Segunda Pantalla'),
);
}
}
And the error message its the next
I/flutter ( 3441): The following assertion was thrown while handling a gesture:
I/flutter ( 3441): Navigator operation requested with a context that does not include a Navigator.
I/flutter ( 3441): The context used to push or pop routes from the Navigator must be that of a widget that is a
I/flutter ( 3441): descendant of a Navigator widget.

When used the MaterialPageRoute you need to send your main class inside of MaterialApp from runApp()
Explain with Code
Correct
void main() => runApp(MaterialApp(
title: 'Oraciones Cristianas',
home: MyApp(),
));
You send yout first Screen insde of MaterialApp(), able to use MaterialPageRoute()
Incorrect
void main() => runApp(myApp());
If you simply send your first screen without MaterialApp() wrapper doesnt works

Use a Builder around your button or around the Column as in the following code:
Builder(
builder: (context) => RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) => SelectUserType()));
},
child: Text('Registrese'),
),
),

Related

Null Check operator used on a null value see also: https://flutter.dev/docs/testing/errors

main.dart :
import 'package:flutter/material.dart';
import 'Scaffold.dart';
main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: Brightness.light,
primaryColor: Colors.amber[500],
accentColor: Colors.blue,
fontFamily: "Georgia",
),
home: myscaffoldfunc()
);
}
}
Scaffold.dart :
import 'package:flutter/material.dart';
onpressedFun() => print("Hello");
myscaffoldfunc(){
Scaffold(
appBar: AppBar(
title: Center(child: Text("Hello")),
),
floatingActionButton: FloatingActionButton(
onPressed: onpressedFun(),
child: Icon(Icons.add),
backgroundColor: Colors.amber,
foregroundColor: Colors.white,
hoverColor: Colors.amberAccent,
),
body: Center(child: Text("Hello World")),
);
}
Everything is working fine when I write the scaffold part in single file but as soon as I make a different file for scaffold it shows the below error in app. Any solution ?
And this error on debug console :-
═════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building Builder(dirty, dependencies: [MediaQuery]):
Null check operator used on a null value
The relevant error-causing widget was
MaterialApp
lib\main.dart:10
When the exception was thrown, this was the stack
#0 _MaterialAppState._materialBuilder
package:flutter/…/material/app.dart:818
#1 _WidgetsAppState.build.<anonymous closure>
package:flutter/…/widgets/app.dart:1545
#2 Builder.build
package:flutter/…/widgets/basic.dart:7798
#3 StatelessElement.build
package:flutter/…/widgets/framework.dart:4648
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4574
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 2 of 554 libraries in 551ms.
Now while running App:-
App
myscaffoldfunc() is void, it doesn't return the Scaffold.
Add a return keyword before Scafold.
HOWEVER, I strongly suggest you using Class instead of Functions for reusable widgets.
Please check this answer.
Your function has no return statement and thus returns null, which is throwing your null error.
Moreover, you should not assign a function to the home parameter, a class would be better.
I would recommed this:
home: Myscaffoldfunc(),
In your other file:
class Myscaffoldfunc extends StatelessWidget {
final Widget child;
const Myscaffoldfunc({Key key, this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text("Hello")),
),
floatingActionButton: FloatingActionButton(
onPressed: onpressedFun(),
child: Icon(Icons.add),
backgroundColor: Colors.amber,
foregroundColor: Colors.white,
hoverColor: Colors.amberAccent,
),
body: Center(child: Text("Hello World")),
);
}
}

Getting error when using a button to access a route in Flutter

Whenever I try to tap the button created in the code below when I load the app,the debug console gives me this error.
════════ Exception caught by gesture ═══════════════════════════════════════════
Could not find a generator for route RouteSettings("/1000hz_route", null) in the _WidgetsAppState.
Here's the code I am attempting to run. How would I go about fixing this error?
import 'package:flutter/material.dart';
import 'package:audiotest/UI/player_widget.dart';
import 'package:flutter/material.dart';
import 'package:audiotest/UI/homepage1.dart';
const flutaud1 =
'https://audio.jukehost.co.uk/694139d474ee606401cc3aa8160159ac14662cd8/093232dd0c4';
void main() => runApp(new MaterialApp(
title: "TestAudio",
initialRoute: '/audio_selection',
routes: {
'/audio_selection': (context) => AudioSelection(),
'/1000hz_route': (context) => MainPersistentTabBar1(),
}));
class AudioSelection extends StatefulWidget {
#override
IntroScreenstate2 createState() => IntroScreenstate2();
}
class IntroScreenstate2 extends State<AudioSelection> {
Widget _tab(List<Widget> children) {
return Center(
child: new Container(
child: new SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
children: children
.map((w) => Container(child: w, padding: EdgeInsets.all(6.0)))
.toList(),
),
),
));
}
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: _tab([
Text(
'Audio 1000 HZ',
style: TextStyle(fontWeight: FontWeight.bold),
),
PlayerWidget(url: flutaud1),
new MaterialButton(
child: new Text('Select 1000 hz'),
onPressed: () {
Navigator.pushNamed(context, '/1000hz_route');
},
),
])
)
);
}
}
I am not sure, but the way I am telling you will get your project up and running. Let me know if it works for you.
Do this inside your onPressed
Navigator.push(context, new MaterialPageRoute(
builder: (context) => MainPersistentTabBar1())
);
Instead of
Navigator.pushNamed(context, '/1000hz_route');

Black screen when using Navigator.push() in Flutter

I'm trying to use Navigator.push to navigate to a new page in Flutter. This is what I've got so far:
GestureDetector(
onTap: () {
print('Test');
// Navigator.push(context,
// MaterialPageRoute(builder: (context) => ResultsPage()));
},
child: Container(
color: Color(0xFFff474b),
child: Center(
child: Text('CALCULATE', style: kButtonText),
),
padding: EdgeInsets.only(bottom: 20.0),
width: double.infinity,
height: 80.0,
margin: EdgeInsets.only(top: 10.0),
),
),
The code that I want to implement is commented out, as I've been testing the onTap with a print statement.
Interestingly, the print statement runs but for some reason, I can't get the Navigator.push to work. It only navigates to a black screen.
For context, this is the Results page - just a simple scaffold with an App Bar. But the App Bar doesn't show up on the next page:
class ResultsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Calculated Distance'),
),
);
}
}
The error may be caused due to two or more Floating Action buttons present in a scaffold. By default Floating Action button has a Hero property active. Make it deactivate by heroTag: null,.
For eg,
FloatingActionButton(
heroTag: null,
child: Icon(),
onPressed: () {},
),
Ahh it turns out that the issues is that I have two FloatingActionButtons on the page, and so it messes with the Navigator route.
This Medium article I found is a nice guide for the solution: https://medium.com/#kaendagger/test-cef30fcb5c54
add ResultsPage() to your routes add this to you MaterialApp(
MaterialApp(
initialRoute: '/',
routes: {
'/': (_) => HOME(),
'/home': (_) => ResultsPage(),
}, )

Flutter Exception caught by gesture. No MediaQuery widget found inside showModalBottomSheet

Why I can't use showModalBottomSheet inside floatingActionButton? It just keeps showing me this error:
I/flutter (16368): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (16368): The following assertion was thrown while handling a gesture:
I/flutter (16368): No MediaQuery widget found.
I/flutter (16368): MyApp widgets require a MediaQuery widget ancestor.
I/flutter (16368): The specific widget that could not find a MediaQuery ancestor was:
I/flutter (16368): MyApp
I/flutter (16368): The ownership chain for the affected widget is: "MyApp ← [root]"
I/flutter (16368): Typically, the MediaQuery widget is introduced by the MaterialApp or WidgetsApp widget at the top of
I/flutter (16368): your application widget tree.
I/flutter (16368):
I/flutter (16368): When the exception was thrown, this was the stack:
I/flutter (16368): #0 debugCheckHasMediaQuery.<anonymous closure> (package:flutter/src/widgets/debug.dart:211:7)
I/flutter (16368): #1 debugCheckHasMediaQuery (package:flutter/src/widgets/debug.dart:223:4)
I/flutter (16368): #2 showModalBottomSheet (package:flutter/src/material/bottom_sheet.dart:469:10)
I/flutter (16368): #3 _MyAppState.build.<anonymous closure> (package:flutter_happy_habits/main.dart:32:29)
I/flutter (16368): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
import 'package:flutter/material.dart';
import './models/home.dart';
import 'models/progress.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _selectedPage = 0;
final _pageOptions = [
Home(),
Progress(),
Progress(),
];
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: true,
home: new Scaffold(
appBar: AppBar(title: Text('Flutter Demo')),
body: _pageOptions[_selectedPage],
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () { showModalBottomSheet(
context: context,
builder: (context) {
return Text('Modal bottom sheet', style: TextStyle(fontSize: 30));
});
}
),
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
notchMargin: 4.0,
child: new Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.home),
onPressed: () {
print("Home");
setState(() {
_selectedPage = 0;
});
},
),
IconButton(
icon: Icon(Icons.insert_chart),
onPressed: () {
print("Progress");
setState(() {
_selectedPage = 1;
});
},
),
],
),
),
),
);
}
}
Its because, the showModalBottomSheet tries to access the ancestor of type MaterialApp from the given context.
Use Builder widget to get new context with MaterialApp ancestor or Separate your MaterialAapp and Scaffold widgets into separate widgets.
Using Builder :
floatingActionButton: Builder(
builder: (context) => FloatingActionButton(
child: Icon(Icons.add),
onPressed: () { showModalBottomSheet(
context: context,
builder: (context) {
return Text('Modal bottom sheet', style: TextStyle(fontSize: 30));
});
}
),
),
I've got a solution. I don't know if it's the best but it works. The showModalBottomSheet should not have the same context as the materialapp, so it must be separated in a statelesswidget as you can see in this example.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter App',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(title: const Text('Modal bottom sheet')),
body: new Center(
child: new RaisedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(context: context, builder: (BuildContext context) {
return new Container(
child: new Padding(
padding: const EdgeInsets.all(32.0),
child: new Text('This is the modal bottom sheet. Click anywhere to dismiss.',
textAlign: TextAlign.center,
style: new TextStyle(
color: Theme.of(context).accentColor,
fontSize: 24.0
)
)
)
);
});
}
)
)
)
);
}
}
you can put the showModalBottomSheet inside Builder() it works with me
body: Padding(
padding: const EdgeInsets.all(8.0),
child: ListView(
children: [
(questionindex < question.length)
? Quiz(question, questionindex, nextquestion)
: Result(playagain),
Builder(
builder: (context) {
return ElevatedButton(
child: Text('Show Modal Bottom Sheet'),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return Wrap(
children: [
ListTile(
leading: Icon(Icons.share),
title: Text('Share'),
),
ListTile(
leading: Icon(Icons.copy),
title: Text('Copy Link'),
),
ListTile(
leading: Icon(Icons.edit),
title: Text('Edit'),
),
],
);
},
);
},
);
},
)
],
),
),

how to fix flutter exception : Navigator operation requested with a context that does not include a Navigator

I am trying to create a drawer navigation using flutter framework,
but i am getting the following exception every time I run it
Another exception was thrown: Navigator operation requested with a
context that does not include a Navigator.
so what is the solution, any help ?
I used Navigator class as the following
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return new AppStates();
}
}
class AppStates extends State<MyApp> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: new Scaffold(
appBar: AppBar(
title: Text("Application App Bar"),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Next Page"),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NextPage()));
},
)
],
),
),
),
);
}
}
and the code of the NextPage class is
class NextPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Next Page App Bar"),
),
),
);
}
}
It looks like you don't have a Navigator setup for current context. Instead of using StatefulWidget you should try MaterialApp as your root App. MaterialApp manages a Navigator for you. Here is an example of how to setup an App in your main.dart
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: MyApp(),
));
}
This is because the context that you're using is from the app level before a Navigator has actually been created. This is a common problem when creating "simple" single file apps in Flutter.
There are a number of possible solutions. One is to extract your Drawer into it's own class (extend Stateless/StatefulWidget accordingly), then in it's build override, the parent Scaffold will have already been created containing a Navigator for you to use.
class MyDrawer extend StatelessWidget {
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Next Page"),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NextPage()));
},
)
],
),
);
}
The other, if you want to keep this Drawer in the same file, is to use a Builder instead, which has the same effect:
drawer: Builder(builder: (context) =>
Drawer(
child: ListView(
children: <Widget>[
ListTile(
title: Text("Next Page"),
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => NextPage()));
},
)
],
),
),
),
you need to create a new Widget as home in MaterialApp like this:-
(This worked for me)
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Title"),
),
body: Center(child: Text("Click Me")),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddTaskScreen()),
);
},
),
);
}
}

Categories

Resources