Flutter for web routing with multiple material apps - flutter

I have an issue regarding the routing of the flutter for the web. For specific reasons in my project, I have multiple material apps. So the platform that I'm building is a material app, let's name it 'Parent'. In this material app at some point lower in the widget tree I have a child that is also a material app let's name it 'Child'. When the user arrives at the point in the Parent tree where Child is rendered, it looks like the routing of Parent is replaced with the actual routing of Child. Is there any way to prevent this from happening?
Since I can't share the actual code I've recreated a minimal example:
import 'package:flutter/material.dart';
void main() {
runApp(ParentApp());
}
class ParentApp extends StatefulWidget {
#override
_ParentAppState createState() => _ParentAppState();
}
class _ParentAppState extends State<ParentApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Parent',
initialRoute: '/parent-home',
routes: {
'/parent-home': (context) => ParentHome(),
'/parent-second': (context) => ParentSecondRoute(),
},
);
}
}
class ParentHome extends StatefulWidget {
#override
_ParentHomeState createState() => _ParentHomeState();
}
class _ParentHomeState extends State<ParentHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body: Container(
child: Center(
child: RaisedButton(
child: Text('Go to second route'),
onPressed: () => Navigator.pushNamed(
context,
'/parent-second',
),
),
),
),
);
}
}
class ParentSecondRoute extends StatefulWidget {
#override
_ParentSecondRouteState createState() => _ParentSecondRouteState();
}
class _ParentSecondRouteState extends State<ParentSecondRoute> {
bool isChildRendered;
#override
void initState() {
isChildRendered = false;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Flexible(
child: isChildRendered
? ChildApp()
: Container(
color: Colors.green,
child: Center(
child: RaisedButton(
child: Text('Go to home'),
onPressed: () => Navigator.of(context).pop(),
),
),
),
),
Flexible(
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Checkbox(
value: isChildRendered,
onChanged: (value) => setState(() {
isChildRendered = value;
}),
),
SizedBox(width: 5),
Text('Is child rendered?'),
],
),
),
)
],
),
);
}
}
class ChildApp extends StatefulWidget {
#override
_ChildAppState createState() => _ChildAppState();
}
class _ChildAppState extends State<ChildApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Child',
initialRoute: '/child-route-i-don\'t-want-to-see',
routes: {
'/child-route-i-don\'t-want-to-see': (context) => Container(
color: Colors.brown,
),
},
);
}
}

Solution with ModalRoute Class
You can solve it this way, by using the ModalRoute Class and passing the current route name defined in its settings as parameter to the Child:
ChildApp(ModalRoute.of(context).settings.name)
class ChildApp extends StatefulWidget {
final String route;
const ChildApp(this.route);
#override
_ChildAppState createState() => _ChildAppState();
}
class _ChildAppState extends State<ChildApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Child',
initialRoute: widget.route,
routes: {
widget.route: (context) => Container(
color: Colors.brown,
),
},
);
}
}
name → String?
The name of the route (e.g., "/settings"). [...]
Full example below:
import 'package:flutter/material.dart';
void main() {
runApp(ParentApp());
}
class ParentApp extends StatefulWidget {
#override
_ParentAppState createState() => _ParentAppState();
}
class _ParentAppState extends State<ParentApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Parent',
initialRoute: '/parent-home',
routes: {
'/parent-home': (context) => ParentHome(),
'/parent-second': (context) => ParentSecondRoute(),
},
);
}
}
class ParentHome extends StatefulWidget {
#override
_ParentHomeState createState() => _ParentHomeState();
}
class _ParentHomeState extends State<ParentHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body: Container(
child: Center(
child: RaisedButton(
child: Text('Go to second route'),
onPressed: () => Navigator.pushNamed(
context,
'/parent-second',
),
),
),
),
);
}
}
class ParentSecondRoute extends StatefulWidget {
#override
_ParentSecondRouteState createState() => _ParentSecondRouteState();
}
class _ParentSecondRouteState extends State<ParentSecondRoute> {
bool isChildRendered;
#override
void initState() {
isChildRendered = false;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Flexible(
child: isChildRendered
? ChildApp(ModalRoute.of(context).settings.name) // this line
: Container(
color: Colors.green,
child: Center(
child: RaisedButton(
child: Text('Go to home'),
onPressed: () => Navigator.of(context).pop(),
),
),
),
),
Flexible(
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Checkbox(
value: isChildRendered,
onChanged: (value) => setState(() {
isChildRendered = value;
}),
),
SizedBox(width: 5),
Text('Is child rendered?'),
],
),
),
)
],
),
);
}
}
class ChildApp extends StatefulWidget {
final String route;
const ChildApp(this.route); // and this one
#override
_ChildAppState createState() => _ChildAppState();
}
class _ChildAppState extends State<ChildApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Child',
initialRoute: widget.route,
routes: {
widget.route: (context) => Container(
color: Colors.brown,
),
},
);
}
}
Home
Second Route

Related

Unable to navigate from GetX Dialog to another screen

I have follow dialog box. When I click 'Next' I want it to navigate to GamePage() screen. But unfortunately it doesn't work.
Following is the GamePage Widget
class GamePage extends StatelessWidget {
final homeCtrl = Get.find<HomeController>();
GamePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF8fb1ca),
body: SafeArea(
child: ListView(
children: [
Padding(
padding: EdgeInsets.all(3.0.wp),
child: Row(
children: [
IconButton(
onPressed: () {
Get.back();
},
icon: const Icon(Icons.arrow_back),
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 4.0.wp),
child: Column(
children: [
SizedBox(
height: 2.0.wp,
),
Center(
child: Text(
'What ${homeCtrl.currentWord.first.wordtype} is this?',
style: TextStyle(
fontSize: 18.0.sp,
color: Colors.grey[800],
),
),
),
SizedBox(height: 10.0.wp),
WordsWidget(currentWord: homeCtrl.currentWord.first),
],
),
),
],
),
),
);
}
}
Following is the Word Widget being called from GamePage Widget
class WordsWidget extends StatelessWidget {
final currentWord;
WordsWidget({Key? key, this.currentWord}) : super(key: key);
final homeCtrl = Get.find<HomeController>();
#override
Widget build(BuildContext context) {
// var currentWord = homeCtrl.nextWord();
var shuffleword = [].obs;
shuffleword.addAll(homeCtrl.shuffleWord(currentWord.word));
TextToSpeech tts = TextToSpeech();
String language = 'en-US';
tts.setLanguage(language);
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
print('pressed here');
Get.defaultDialog(
title: 'Go to next page',
content: Container(
child: Column(
children: [
Text('You are about to move to another screen'),
ElevatedButton.icon(
onPressed: () {
Get.to(() => GamePage());
},
icon: Icon(
Icons.arrow_right,
),
label: Text('Go'))
],
),
));
},
child: Text('Open Dialog')),
],
);
}
}
Get.back() is working but not Get.to
Try
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return const GamePage();
},
),
);
},
child: Text("Next Word"),
)
Try this code -
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_memory/next_page.dart';
import 'package:image_picker/image_picker.dart';
void main() {
//check getMaterialApp is used
runApp(const GetMaterialApp(
title: 'Temp',
home: const MyApp(),
));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Image Picker'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
print('pressed here');
Get.defaultDialog(
title: 'Go to next page',
content: Container(
child: Column(
children: [
Text('You are about to move to another screen'),
ElevatedButton.icon(
onPressed: () {
Get.to(() => NextPage());
},
icon: Icon(
Icons.arrow_right,
),
label: Text('Go'))
],
),
));
},
child: Text('Open Dialog')),
),
);
}
}
and next page is -
import 'package:flutter/material.dart';
class NextPage extends StatefulWidget {
const NextPage({ Key? key }) : super(key: key);
#override
State<NextPage> createState() => _NextPageState();
}
class _NextPageState extends State<NextPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Next Page'),
),
body: Container(
child: Center(
child: Text("this is next page"),
),
),
);
}
}
And yes, you need to insure that you are using 'GetMaterialApp'.
If you want to use GetX navigation system, you should wrap your application in a GetMaterialApp instead of MaterialApp.
So in your main use this:
class GetxApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return GetMaterialApp(
home: HomePage(),
);
}
}
Instead of this:
class NormalApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

Alert dialogue not displaying even with show dialogue

I changed it to stateful and used return dialogue but still nothing.
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
createAlertDialogue(BuildContext context) {
TextEditingController customeController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(" Your NAme"),
content: TextField(
controller: customeController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('submit'),
onPressed: () {},
)
],
);
});
}
Widget _buildForgotPasswordBtn(BuildContext ctx) {
return Container(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
setState(() {
createAlertDialogue(ctx);
});
},
child: Text(
'forgot password',
style: kLabelStyle,
),
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromARGB(206, 5, 42, 146),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildForgotPasswordBtn(context),
],
),
),
),
);
}
}
I used setState and even put ctx in createalertdialogue because it didn't work until I changed from context to this.
I don't get any errors but I get nothing when I press the forgot password button on the emulator.
The button is there and can be pressed with no errors but still nothing appears.
i fixed it nevermind sorry the answer was changing the navigation method to Navigator.pushNamed
I Just slightly edited your code
Wrap your runApp with MaterialApp
from
void main() {
runApp(
MyApp(),
);
}
to
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
your full code
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
createAlertDialogue(BuildContext context) {
TextEditingController customeController = TextEditingController();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(" Your NAme"),
content: TextField(
controller: customeController,
),
actions: <Widget>[
MaterialButton(
elevation: 5.0,
child: Text('submit'),
onPressed: () {},
)
],
);
});
}
Widget _buildForgotPasswordBtn(BuildContext ctx) {
return Container(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
setState(() {
createAlertDialogue(ctx);
});
},
child: Text(
'forgot password',
),
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromARGB(206, 5, 42, 146),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_buildForgotPasswordBtn(context),
],
),
),
),
);
}
}

Flutter setState public var to another page?

how to setState public var to another page?
int x = 1;
that was in public
in the first page text(x) i want to setstate from the other page
my first page is
class AddFullRequest extends StatefulWidget {
#override
_AddFullRequestState createState() => _AddFullRequestState();
}
class _AddFullRequestState extends State<AddFullRequest> {
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Text(x),
GestureDetector(
onTap: (){
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context) => AddItemScr()));
},
child: Text('goto'),
),
],
),
);
}
in the other page button to ++ the var in the first page
my other page is
class AddItemScr extends StatefulWidget {
#override
_AddItemScrState createState() => _AddItemScrState();
}
class _AddItemScrState extends State<AddItemScr> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: WillPopScope(onWillPop: (){
Navigator.of(context).pop();
},
child: Column(
children: <Widget>[
FlatButton(onPressed: (){setState(() {
x++;
});}, child: Text('pluss'),)
],
),
),
);
}
}
please help me with this
You can use the callback pattern. In this example, a function (onPressed) is passed to the child. The child calls the function when a button is pressed:
class AddFullRequest extends StatefulWidget {
#override
_AddFullRequestState createState() => _AddFullRequestState();
}
class _AddFullRequestState extends State<AddFullRequest> {
int _x = 0;
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Text("$_x"),
GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddItemScr(
onPressed: () => setState(() => _x++),
),
),
);
},
child: Text('goto'),
),
],
),
);
}
}
class AddItemScr extends StatelessWidget {
final VoidCallback onPressed;
const AddItemScr({
Key key,
#required this.onPressed,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
FlatButton(
onPressed: onPressed,
child: Text('Increment'),
),
],
),
);
}
}
You can pass variables between screens. NavigatorState#pop supports passing objects that you can await in the previous screen and set it to it's value.
class AddFullRequest extends StatefulWidget {
#override
_AddFullRequestState createState() => _AddFullRequestState();
}
class _AddFullRequestState extends State<AddFullRequest> {
int x = 0;
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Text('$x'),
GestureDetector(
onTap: () async {
final result = await Navigator.of(context).push<int>(
MaterialPageRoute(
builder: (_) => AddItemScr(variable: x),
),
);
x = result;
setState(() {});
},
child: Text('goto'),
),
],
),
);
}
}
class AddItemScr extends StatefulWidget {
final int variable;
AddItemScr({this.variable});
#override
_AddItemScrState createState() => _AddItemScrState();
}
class _AddItemScrState extends State<AddItemScr> {
int _variable;
#override
void initState() {
_variable = widget.variable;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
FlatButton(
onPressed: () {
setState(() {
_variable++;
});
},
child: Text('pluss'),
),
FlatButton(
onPressed: () {
Navigator.of(context).pop(_variable);
},
child: Text('go back'),
),
],
),
);
}
}

How to pass data to a widget inside of another widget

I was able to pass the data widget.value from the FirstPage to SecondPage. There's a widget called thirdWidget inside SecondPage.
How do I pass widget.value to thirdWidget?
class FirstPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => FirstPageState();
}
class FirstPageState extends State< FirstPage > {
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Column(
children: <Widget>[
TextField(
controller: myController,
decoration: new InputDecoration(labelText: "Enter a number"),
keyboardType: TextInputType.number,
),
RaisedButton(
child: Text("show text"),
onPressed: () {
return Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ThirdRoute(
selectedDate: selectedDate,
value: myController.text,
)),
);
},
);
},
),
],
),
);
}
}
class SecondPage extends StatefulWidget {
final String value;
ThirdRoute({Key key, this.value})
: super(key: key);
#override
SecodpageState createState() => SecodpageState();
}
class SecodpageState extends State< SecondPage > {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Calendar Page"),
),
body: Column(
children: <Widget>[
Text("${widget.value}"),
Row(
children: thirdWidget(),
),
Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
],
),
);
}
}
List<Widget> thirdWidget() {
return Text("${widget.value}”)
}
Use this in your SecondPage
Row(
children: thirdWidget(widget.value),
)
And update your thirdWidget like:
List<Widget> thirdWidget(var data) {
// data is widget.value
return [];
}
Just pass that info into the state class. Something like that:
class SecondPage extends StatefulWidget {
final String value;
ThirdRoute({Key key, this.value})
: super(key: key);
#override
SecodpageState createState() => SecodpageState(value);
}
class SecodpageState extends State< SecondPage > {
final String value;
SecodpageState(this.value);
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Calendar Page"),
),
body: Column(
children: <Widget>[
Text("${widget.value}"),
Row(
children: thirdWidget(),
),
Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
],
),
);
}
}
List<Widget> thirdWidget() {
return Text(value);
}

How to intercept flutter back-button when keyboard is shown

I want to intercept the back-button of the soft keyboard in flutter. So when I want to close the keyboard by pressing the back-button I want an additional function to be called.
How can I do that?
Keyboard Back button
you can use the keyboard_visibility package to achieve this.
Working Example
the following code displays a SnackBar once the keyboard is dismissed.
import 'package:flutter/material.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GlobalKey<ScaffoldState> _key;
#override
void initState() {
super.initState();
_key = GlobalKey<ScaffoldState>();
KeyboardVisibilityNotification().addNewListener(
onHide: () {
_key.currentState.showSnackBar(
SnackBar(
content: Text("Keyboard closed"),
),
);
},
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _key,
body: Center(
child: TextField(),
),
),
);
}
}
you can use the https://pub.dev/packages/flutter_keyboard_visibility package to achieve this.
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_keyboard_visibility_example/keyboard_dismiss_demo.dart';
import 'package:flutter_keyboard_visibility_example/provider_demo.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Demo(),
);
}
}
class Demo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return KeyboardDismissOnTap(
child: Scaffold(
appBar: AppBar(
title: Text('Keyboard Visibility Example'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProviderDemo()),
);
},
child: Text('Provider Demo'),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => KeyboardDismissDemo()),
);
},
child: Text('KeyboardDismiss Demo'),
),
Spacer(),
TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Input box for keyboard test',
),
),
Container(height: 60.0),
KeyboardVisibilityBuilder(builder: (context, visible) {
return Text(
'The keyboard is: ${visible ? 'VISIBLE' : 'NOT VISIBLE'}',
);
}),
Spacer(),
],
),
),
),
),
);
}
}