How to call ExitPopUp widgets from other pages in Flutter? - flutter

I wrote a code for ExitPopUp on a single page. Here is the code -
import 'package:flutter/material.dart';
class ExitPopUp extends StatelessWidget {
final page;
ExitPopUp(this.page);
#override
Widget build(BuildContext context) {
Future<bool> showExitPopUp() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Confirm"),
content: Text("Do you want to Exit ?"),
actions: <Widget>[
RaisedButton(child: Text("No"), onPressed: null),
RaisedButton(child: Text("Yes "), onPressed: null)
],
);
});
}
return WillPopScope(child: page, onWillPop: showExitPopUp);
}
}
Now I want to call this ExitPopUp from other page (***example:* registration.dart)**. Here is the code of Registration page-
import 'package:bloodhero/widgets/drawer.dart';
import 'package:bloodhero/widgets/exitpop.dart';
import 'package:flutter/material.dart';
import 'package:bloodhero/widgets/form.dart';
class Registration extends StatefulWidget {
#override
_RegistrationState createState() => _RegistrationState();
}
class _RegistrationState extends State<Registration> {
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
print("Hey I am Dialog Box");
return ExitPopUp();
},
child: Scaffold(
appBar: AppBar(
title: Text("Registration"),
backgroundColor: Colors.deepOrange,
),
drawer: DrawerApp(),
body: ListView(
children: <Widget>[
FormPage(),
],
)));
}
}
But It's not working. Error show in OnWillPop.
How can I fix it?

You can copy paste run full code below
You can pass Scaffold part code as parameter of ExitPopUp
code snippet
class _RegistrationState extends State<Registration> {
#override
Widget build(BuildContext context) {
return ExitPopUp(Scaffold(
appBar: AppBar(
title: Text("Registration"),
backgroundColor: Colors.deepOrange,
),
//drawer: DrawerApp(),
body: ListView(
children: <Widget>[
Text("FormPage()"),
],
)));
}
}
working demo
full code
import 'package:flutter/material.dart';
class ExitPopUp extends StatelessWidget {
final page;
ExitPopUp(this.page);
#override
Widget build(BuildContext context) {
Future<bool> showExitPopUp() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Confirm"),
content: Text("Do you want to Exit ?"),
actions: <Widget>[
RaisedButton(child: Text("No"), onPressed: (){}),
RaisedButton(child: Text("Yes "), onPressed: null)
],
);
});
}
return WillPopScope(child: page, onWillPop: showExitPopUp);
}
}
class Registration extends StatefulWidget {
#override
_RegistrationState createState() => _RegistrationState();
}
class _RegistrationState extends State<Registration> {
#override
Widget build(BuildContext context) {
return ExitPopUp(Scaffold(
appBar: AppBar(
title: Text("Registration"),
backgroundColor: Colors.deepOrange,
),
//drawer: DrawerApp(),
body: ListView(
children: <Widget>[
Text("FormPage()"),
],
)));
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Registration(),
);
}
}

Related

Flutter using a changenotifier with named routes

I've followed some online tutorials and managed to implement ChangeNotifier when the app has a single route however none of these explain how to implement this when the app has more than one route (screen) which is rather the point!
I made an attempt to figure this out myself but when the app runs in the emulator I get a blank screen.
/* main.dart */
import 'dart:collection'; // used in test.dart
import 'package:flutter/foundation.dart'; // used in test.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Person extends ChangeNotifier {
Person({this.firstName});
String firstName = '';
void updateName(String n) {
this.firstName = n;
notifyListeners();
}
}
void main() {
runApp(
Provider(
create: (_) => Person(firstName: 'Mark'),
child: MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeRoute(),
'/second': (context) => SecondRoute(),
'/third': (context) => ThirdRoute(),
},
),
)
);
}
class HomeRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(Provider.of<Person>(context).firstName),
),
body: Center(
child: new IconButton(
icon: new Icon(Icons.favorite, color: Colors.redAccent),
iconSize: 70.0,
onPressed: () {
Navigator.of(context).pushNamed("/second");
}
),
),
);
}
}
class SecondRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Page'),
),
body: Center(
child: Text(Provider.of<Person>(context).firstName),
),
);
}
}
class ThirdRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Third Page'),
),
body: Center(
child: Text('Third Route'),
),
);
}
}
The project builds and runs with no error messages which has stumped me.
Any thoughts?
Code developed in FlutLab

How can i use flutter drawer menu in page routing?

i am new to flutter also coding.
what i want to do:
to add drawer menu to main.dart, it will return Scaffold for all pages in the menu.
in every page i want to use different Scaffold. (appbar & body)
i created pages, routes, drawer; but i couldn't add drawer to pages and also in the Builder(main.dart), i think i have some mistakes.
main.dart is like this:
import 'package:flutter/material.dart';
import 'package:letter_app/screens/user/postbox.dart';
import 'package:letter_app/screens/user/unread.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
int selectedMenuItem = 0;
final pageOptions = [
PostBox(),
Unread(),
];
Widget buildDrawer(BuildContext context) {
return Drawer(
child: ListView(
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(),
),
ListTile(
title: Text('Unread'),
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => new Unread()));
Navigator.pop(context);
},
),
ListTile(
title: Text('Post Box'),
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => new PostBox()));
Navigator.pop(context);
},
),
],
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'New App',
theme: ThemeData.dark(),
routes: <String, WidgetBuilder>{
'/screens/user/unread.dart': (BuildContext context) => Unread(),
'/screens/user/postbox.dart': (BuildContext context) => PostBox(),
},
home: Builder(
builder: (context) => Scaffold(
drawer: buildDrawer(context),
body: Container(child: pageOptions[selectedMenuItem]),
),
),
);
}
}
unread.dart is like this:
import 'package:flutter/material.dart';
class Unread extends StatefulWidget {
#override
_UnreadState createState() => _UnreadState();
}
class _UnreadState extends State<Unread> {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: ,
appBar: AppBar(
title: Text('Welcome to Flutter'),
),
body: Center(
child: Text('Unread'),
),
);
}
}
Just define the buildDrawer widget in a seperate dart file, import the file. Then, just assign it to every Scaffold.

Showing a dialog that is in another file in flutter app

I'm trying to show a dialog box that is in another file in a StatefullWidget but when I call its function nothing is happening.
The reason I want to do this is because there is too much nesting of code in my code so I want to keep things simple and clean.
Below is the dialog.dart file.
import 'package:flutter/material.dart';
class PersonDetailsDialog extends StatefulWidget {
PersonDetailsDialog({Key key}) : super(key: key);
#override
_PersonDetailsDialogState createState() {
return _PersonDetailsDialogState();
}
}
class _PersonDetailsDialogState extends State<PersonDetailsDialog> {
#override
Widget build(BuildContext context) {
Future<void> _neverSatisfied() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Rewind and remember'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('You will never be satisfied.'),
Text('You\’re like me. I’m never satisfied.'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Regret'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
}
Below is the main.dart file.
mport 'package:flutter/material.dart';
import 'package:practical_0/homepage.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue
),
home: Homepage(),
);
}
}
Below is homepage.dart file where I'm trying to show the dialog when the user clicks RaisedButton but nothing happens.
import 'package:flutter/material.dart';
class Homepage extends StatelessWidget {
final double heightFactor = 600/896;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: RaisedButton(
onPressed: PersonDetailsDialog(), // show dialog
),
),
);
}
}
You have to use ShowDialog Where You want to show dialog.
I hope that following example clear your idea.
class Delete extends StatefulWidget {
#override
_DeleteState createState() => _DeleteState();
}
class _DeleteState extends State<Delete> {
BuildContext parent, child;
#override
Widget build(BuildContext context) => Scaffold(
body: Container(
child: Center(
child: RaisedButton(
onPressed: () {
showDialog(
context: context,
barrierDismissible: false,
child: PersonDetailsDialog());
}, // show dialog
),
),
),
);
}
class PersonDetailsDialog extends StatefulWidget {
PersonDetailsDialog({Key key}) : super(key: key);
#override
_PersonDetailsDialogState createState() {
return _PersonDetailsDialogState();
}
}
class _PersonDetailsDialogState extends State<PersonDetailsDialog> {
#override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Rewind and remember'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('You will never be satisfied.'),
Text('You\’re like me. I’m never satisfied.'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Regret'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
}
Here is an example:
Show dialog is an async function
child: RaisedButton(
onPressed: () async{
final result = await showDialog(
context: context,
builder: (_) => AlertWidget(),
);
return result;
},

Flutter app back button event not redirecting to back page

I am developing a flutter android app. It have three screens. Page 1, Page 2, Page 3. When i entering Page 3 from Page 2. if i click phone back button it want to got to page 2.
But it is redirecting to page 1. I tried after got the reference from
catch Android back button event on Flutter
I tried WillPopScope . It is not entering in onWillPop .
How to solve the problem. My code is shown below.
page 1
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(
appBar: new AppBar(),
body: MyAppPage()
),
);
}
}
class MyAppPage extends StatefulWidget{
MyAppPage({Key key,}):super(key:key);
#override
_MyAppPageState createState()=> new _MyAppPageState();
}
class _MyAppPageState extends State<MyAppPage>{
#override
Widget build(BuildContext context){
return new Scaffold(
body:RaisedButton(onPressed:(){ Navigator.push(context, MaterialPageRoute(builder: (context) => SecondScreen()));},
child: new Text("got to page 1"),)
);
}
}
page 2
class SecondScreen extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: new AppBar(),
body: SecondPage()
),
);
}
}
class SecondPage extends StatefulWidget{
SecondPage({Key key,}):super(key:key);
#override
SecondPageState createState()=> new SecondPageState();
}
class SecondPageState extends State<SecondPage>{
#override
Widget build(BuildContext context){
return new Scaffold(
body:Column(
children: <Widget>[
new Center(
child: new Text("Page 2"),
),
RaisedButton(onPressed:(){ Navigator.push(context, MaterialPageRoute(builder: (context) => ThirdScreen()));},
child: new Text("go to third Page 3"),)
],
)
);
}
}
page 3
class ThirdScreen extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: new AppBar(),
body: ThirdPage()
),
);
}
}
class ThirdPage extends StatefulWidget{
ThirdPage({Key key,}):super(key:key);
#override
ThirdPageState createState()=> new ThirdPageState();
}
class ThirdPageState extends State<ThirdPage>{
#override
Widget build(BuildContext context){
return new WillPopScope(
child: new Scaffold(
body: new Center(
child: new Text('PAGE 3'),
),
),
onWillPop: (){
debugPrint("onWillPop");
return new Future(() => false);
},
);
}
}
You kinda got confused with the Screen and Pages you created. You actually have more Widgets than you need.
This is what you probably want to do.
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: MyAppPage());
}
}
class MyAppPage extends StatefulWidget {
#override
_MyAppPageState createState() => _MyAppPageState();
}
class _MyAppPageState extends State<MyAppPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 1")),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(child: Text("got to page 1")),
RaisedButton(
child: Text("Go to Page 2"),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage()));
},
),
],
),
);
}
}
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 2")),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(
child: Text("I'm in Page 2"),
),
RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ThirdPage()));
},
child: Text("go to third Page 3"),
)
],
)
);
}
}
class ThirdPage extends StatefulWidget {
#override
_ThirdPageState createState() => _ThirdPageState();
}
class _ThirdPageState extends State<ThirdPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Page 3")),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Center(child: Text('PAGE 3')),
RaisedButton(
child: Text("aditional back button"),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
}
}
On your 3rd page, try to use
onWillPop: () {
Navigator.of(context).pop();
},
for my case, I should upgrade the flutter master branch to the latest code.
flutter channel master
flutter upgrade --force
flutter doctor -v

Navigator operation requested with a context that does not include a Navigator

I'm trying to start a new screen within an onTap but I get the following error:
Navigator operation requested with a context that does not include a
Navigator.
The code I am using to navigate is:
onTap: () { Navigator.of(context).pushNamed('/settings'); },
I have set up a route in my app as follows:
routes: <String, WidgetBuilder>{
'/settings': (BuildContext context) => new SettingsPage(),
},
I've tried to copy the code using the stocks sample application. I've looked at the Navigator and Route documentation and can't figure out how the context can be made to include a Navigator. The context being used in the onTap is referenced from the parameter passed into the build method:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
SettingsPage is a class as follows:
class SettingsPage extends Navigator {
Widget buildAppBar(BuildContext context) {
return new AppBar(
title: const Text('Settings')
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: buildAppBar(context),
);
}
}
TLDR: Wrap the widget which needs to access to Navigator into a Builder or extract that sub-tree into a class. And use the new BuildContext to access Navigator.
This error is unrelated to the destination. It happens because you used a context that doesn't contain a Navigator instance as parent.
How do I create a Navigator instance then ?
This is usually done by inserting in your widget tree a MaterialApp or WidgetsApp. Although you can do it manually by using Navigator directly but less recommended. Then, all children of such widget can access NavigatorState using Navigator.of(context).
Wait, I already have a MaterialApp/WidgetsApp !
That's most likely the case. But this error can still happens when you use a context that is a parent of MaterialApp/WidgetsApp.
This happens because when you do Navigator.of(context), it will start from the widget associated to the context used. And then go upward in the widget tree until it either find a Navigator or there's no more widget.
In the first case, everything is fine. In the second, it throws a
Navigator operation requested with a context that does not include a Navigator.
So, how do I fix it ?
First, let's reproduce this error :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
),
);
}
}
This example creates a button that attempts to go to '/' on click but will instead throw an exception.
Notice here that in the
onPressed: () => Navigator.pushNamed(context, "/"),
we used context passed by to build of MyApp.
The problem is, MyApp is actually a parent of MaterialApp. As it's the widget who instantiate MaterialApp! Therefore MyApp's BuildContext doesn't have a MaterialApp as parent!
To solve this problem, we need to use a different context.
In this situation, the easiest solution is to introduce a new widget as child of MaterialApp. And then use that widget's context to do the Navigator call.
There are a few ways to achieve this. You can extract home into a custom class :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHome()
);
}
}
class MyHome extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
);
}
}
Or you can use Builder :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
),
),
);
}
}
Hy guys, i have the same problem. This is occur for me. The solution what i found is very simple. Only what i did is in a simple code:
void main() {
runApp(MaterialApp(
home: YOURAPP() ,
),
);
}
I hope was useful.
Make sure your current parent widget not with same level with MaterialApp
Wrong Way
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Title'),
),
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: RaisedButton(
onPressed: () {
//wrong way: use context in same level tree with MaterialApp
Navigator.push(context,
MaterialPageRoute(builder: (context) => ScanScreen()));
},
child: const Text('SCAN')),
)),
),
);
}
}
Right way
void main() => runApp(MaterialApp(
title: "App",
home: HomeScreen(),
));
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Title'),
),
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: RaisedButton(
onPressed: () {
//right way: use context in below level tree with MaterialApp
Navigator.push(context,
MaterialPageRoute(builder: (context) => ScanScreen()));
},
child: const Text('SCAN')),
)),
);
}
}
Just like with a Scaffold you can use a GlobalKey. It doesn't need context.
final _navKey = GlobalKey<NavigatorState>();
void _navigateToLogin() {
_navKey.currentState.popUntil((r) => r.isFirst);
_navKey.currentState.pushReplacementNamed(LoginRoute.name);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: _navKey,
...
);
}
I set up this simple example for routing in a flutter app:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
routes: <String, WidgetBuilder>{
'/settings': (BuildContext context) => new SettingsPage(),
},
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('TestProject'),
),
body: new Center(
child: new FlatButton(
child: const Text('Go to Settings'),
onPressed: () => Navigator.of(context).pushNamed('/settings')
)
)
);
}
}
class SettingsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('SettingsPage'),
),
body: new Center(
child: new Text('Settings')
)
);
}
}
Note, that the SettingsPage extends StatelessWidget and not Navigator. I'm not able to reproduce your error.
Does this example help you in building your app? Let me know if I can help you with anything else.
You should rewrite your code in main.dart
FROM:
void main() => runApp(MyApp());
TO
void main() {
runApp(MaterialApp(
title: 'Your title',
home: MyApp(),));}
The point is to have the home property to be your first page
this worked for me, I hope it will help someone in the future
A complete and tested solution:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:my-app/view/main-view.dart';
class SplashView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: Builder(
builder: (context) => new _SplashContent(),
),
routes: <String, WidgetBuilder>{
'/main': (BuildContext context) => new MainView()}
);
}
}
class _SplashContent extends StatefulWidget{
#override
_SplashContentState createState() => new _SplashContentState();
}
class _SplashContentState extends State<_SplashContent>
with SingleTickerProviderStateMixin {
var _iconAnimationController;
var _iconAnimation;
startTimeout() async {
var duration = const Duration(seconds: 3);
return new Timer(duration, handleTimeout);
}
void handleTimeout() {
Navigator.pushReplacementNamed(context, "/main");
}
#override
void initState() {
super.initState();
_iconAnimationController = new AnimationController(
vsync: this, duration: new Duration(milliseconds: 2000));
_iconAnimation = new CurvedAnimation(
parent: _iconAnimationController, curve: Curves.easeIn);
_iconAnimation.addListener(() => this.setState(() {}));
_iconAnimationController.forward();
startTimeout();
}
#override
Widget build(BuildContext context) {
return new Center(
child: new Image(
image: new AssetImage("images/logo.png"),
width: _iconAnimation.value * 100,
height: _iconAnimation.value * 100,
)
);
}
}
As per this comment If your navigator is inside Material context navigator push will give this error. if you create a new widget and assign it to the material app home navigator will work.
This won't work
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: new Center(child: new Text("Click Me")),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new AddTaskScreen()),
);
},
),
),
);
}
}
This will work
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: new Center(child: new Text("Click Me")),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new AddTaskScreen()),
);
},
),
);
}
}
I was facing the same problem and solved by removing home from MaterialApp and use initialRoute instead.
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => MyApp(),
'/settings': (context) => SettingsPage(),
},
);
And
onTap: () => {
Navigator.pushNamed(context, "/settings")
},
It is Simple
instead using this normal code
`runApp(BasicBankingSystem());`
wrap it with MaterialApp
runApp(MaterialApp(home: BasicBankingSystem()));
It happens because the context on the widget that tries to navigate is still using the material widget.
The short answer for the solution is to :
extract your widget
that has navigation to new class so it has a different context when calling the navigation
When your screen is not navigated from other screen,you don't initially have access to the navigator,Because it is not instantiated yet.So in that case wrap your widget with builder and extract context from there.This worked for me.
builder: (context) => Center(
child: RaisedButton(
child: Text("Foo"),
onPressed: () => Navigator.pushNamed(context, "/"),
),
You ca use this plugin
https://pub.dev/packages/get/versions/2.0.2
in The MaterialApp assign property navigatorKey: Get.key,
MaterialApp(
navigatorKey: Get.key,
initialRoute: "/",
);
you can access Get.toNamed("Your route name");
Change your main function example:
void main() {
runApp(
MaterialApp(
title: 'Your title',
home: MyApp(),
)
);
}
use this
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),);
}
instead of this
void main() {runApp(MyApp());}
Wrap with materialapp
reproduce code
import 'dart:convert';
import 'package:flutter/material.dart';
void main() {
// reproduce code
runApp(MyApp());
// working switch //
// runApp(
//
// MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body:
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 100,
width: 100,
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => IntroPage(Isscar4: true)),
);
},
child: RichText(
text: TextSpan(
text: 'CAR',
style: TextStyle(
letterSpacing: 3,
color: Colors.white,
fontWeight: FontWeight.w400),
children: [
TextSpan(
text: '4',
style: TextStyle(
fontSize: 25,
color: Colors.red,
fontWeight: FontWeight.bold))
],
)),
),
),
],
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 100,
width: 100,
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => IntroPage(Isscar4: false)),
);
},
child: RichText(
text: TextSpan(
text: 'BIKE',
style: TextStyle(
letterSpacing: 3,
color: Colors.white,
fontWeight: FontWeight.w400),
children: [
TextSpan(
text: '2',
style: TextStyle(
fontSize: 25,
color: Colors.red,
fontWeight: FontWeight.bold))
],
)),
),
),
],
)
])));
}
MaterialApp Swithwidget(istrue) {
return MaterialApp(
home: Scaffold(
body: IntroPage(
Isscar4: istrue,
),
),
);
}
}
class Hi extends StatelessWidget {
const Hi({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
child: Text("df"),
);
}
}
class IntroPage extends StatelessWidget {
final Isscar4;
IntroPage({
Key? key,
required this.Isscar4,
}) : super(key: key);
List<Widget> listPagesViewModel = [];
List<IntroModel> models = [];
#override
Widget build(BuildContext context) {
List<dynamic> intro = fetchIntroApi(Isscar4);
intro.forEach((element) {
var element2 = element as Map<String, dynamic>;
var cd = IntroModel.fromJson(element2);
models.add(cd);
});
models.forEach((element) {
listPagesViewModel.add(Text(""));
});
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(),
));
}
List fetchIntroApi(bool bool) {
var four = bool;
if (four) {
var data =
'[ {"name_Title": "title name1","description": "description1"}, {"name_Title": "title name2","description": "description2"}, {"name_Title": "title name3","description": "description3"}, {"name_Title": "title name4","description": "description4"} ]';
return json.decode(data);
} else {
var data =
'[ {"name_Title": "title name","description": "description1"}, {"name_Title": "title name2","description": "description2"}, {"name_Title": "title name3","description": "description3"} ]';
return json.decode(data);
}
}
}
class IntroModel {
String? nameTitle;
String? description;
IntroModel({this.nameTitle, this.description});
IntroModel.fromJson(Map<String, dynamic> json) {
nameTitle = json['name_Title'];
description = json['description'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name_Title'] = this.nameTitle;
data['description'] = this.description;
return data;
}
}
class Splash extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Splash Screen',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MyState(),
debugShowCheckedModeBanner: false,
);
}
void main() {
runApp(Splash());
}
class MyState extends StatefulWidget{
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyState> {
#override
void initState() {
super.initState();
Timer(Duration(seconds: 3),
()=>Navigator.pushReplacement(context,
MaterialPageRoute(builder:
(context) =>
Login()
)
)
);
}
#override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center ,
children: [
Container(
child:
Image.asset("assets/images/herosplash.png"),
),
],
),
);
}
}
Builder(
builder: (context) {
return TextButton(
child: const Text('Bearbeiten'),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const gotothesiteyouwant()),
);
});
}
),
Here, all you need is to make MaterialApp the parent of your Build. This is because the context that you've used to navigate to a different screen is finding a MaterialApp or a WidgetApp as a parent of the build.
And Since in your case, the situation is the opposite, therefore you need to modify it by either calling a new Stateless widget the parent of is the MaterialApp or by simply using a Builder as home: Builder in MaterialApp.
Hope this would help!