Skip to main content

Flutter Page Navigation and Send data to Page


Flutter Page Navigation, If you are from the Kotlin or Java and witting the Android app using the Android Studio then you are well aware of the Activity and Fragment. But in the Flutter, there is no activity and fragment. So question is that what is alternative of this and the answer is Page/Widget. So in this article, we will explore how to navigate from one page to other pages, send and receive data to the page step by step.





The Home Page of Flutter





When we create the project by default we get one page created and it's defined as home. If you are new to Flutter and Dart then please check our earlier article. There is no restriction on the page definition so you can give any page as the home page.





class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Navigation Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Page Navigation Demo'),
);
}
}




So in the above code, the first page defined as MyHomePage with the title as an argument.





 home: MyHomePage(title: 'Flutter Page Navigation Demo'),




We are cleaning the default logic of the home screen(MyHomePage class) and after modification, it will look like as given below.





class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(onPressed: () {},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),

)
],
),
),
);
}
}




Flutter Page Navigation to Second Page





We are going to create a second page which will be similar to the Home page. Just you can copy-paste the above code an modify as given below.





class MySecondPage extends StatefulWidget {
MySecondPage({Key key, this.title}) : super(key: key);
final String title;
@override
_MySecondPageState createState() => _MySecondPageState();
}

class _MySecondPageState extends State<MySecondPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Page"),
),
body: Center(
child: Container(
child: Text("This is the Second Activity",style: TextStyle(fontSize: 18),),
),
),
);
}
}




Now we need to modify our First Page i.e MyHomePage class Raised Button onPressed method to navigate to the second page like given below.





  RaisedButton(onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) =>MySecondPage()));
},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),
)




Flutter Page Naivation




The full code of the above example





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(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Page Navigation Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) =>MySecondPage(title: "Second Page",)));
},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),

)
],
),
),
);
}
}
class MySecondPage extends StatefulWidget {
MySecondPage({Key key, this.title}) : super(key: key);
final String title;
@override
_MySecondPageState createState() => _MySecondPageState();
}

class _MySecondPageState extends State<MySecondPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("${widget.title}"),
),
body: Center(
child: Container(
child: Text("This is the Second Activity",style: TextStyle(fontSize: 18),),
),
),
);
}
}




Flutter Send Data to Second Page





We have successfully navigated to the second activity and using the default back button we are able to come back to the home page as well. However, we can use the pop method of the navigator as well go back. So now we are going to send some data to of second activity.





Flutter uses the named variable to send the data to others page. If you notice there already a default named parameter in the above example that is the title. But we will create more structured data, for example, we want to send custom datatype which is a combination of the title and message.






class Data{
String title;
String message;
Data(this.title,this.message);
}




Above is the simple POJO class to hold the title and message.





So to send that same to the second page we need to add a named variable of the Data in our second activity.





 MySecondPage({Key key, this.data}) : super(key: key);
Data data;




Named parameters come under the curly braces as given above. Now we need to some change to send the data from the first activity.





RaisedButton(onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) =>MySecondPage(data:
new Data("Second Activity","I am coming from First Activity"),)));
},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),

)




How to use the data inside the second Activity





We can access the data sent by the first activity to anywhere inside the widget by widget.data.message like given below.





class _MySecondPageState extends State<MySecondPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("${widget.data.title}"),
),
body: Center(
child: Container(
child: Text("Message: ${widget.data.message}",style: TextStyle(fontSize: 20),),
),
),
);
}
}




Receive data from the Second Page in Flutter





So for receiving the data from the second activity we need to use async and await function and pop the second Page with some data. So, first of all, we are creating a variable to hold the result returned from the second activity inside the MyHomePage class.





 var result="Waitting for data";




Modify the MyHomePage as given below.





 RaisedButton(onPressed: () async {
widget.result= await Navigator.push(context,
MaterialPageRoute(
builder: (context) =>MySecondPage(data:
new Data("Second Activity","I am coming from First Activity"),)));
},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),

),
Text("${widget.result}"),




Here widget.result will store the value whatever returned from the second activity. Using the await we are waiting for the result.





Page Navigation with data return




Full code of the above example as given below.





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(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Page Navigation Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
var result="Waitting for data";
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(onPressed: () async {
widget.result= await Navigator.push(context,
MaterialPageRoute(
builder: (context) =>MySecondPage(data:
new Data("Second Activity","I am coming from First Activity"),)));
},
child: Text("Go to the Next Page",style: TextStyle(fontSize: 20),),

),
Text("${widget.result}"),
],
),
),
);
}
}
class MySecondPage extends StatefulWidget {
MySecondPage({Key key, this.data}) : super(key: key);
Data data;
@override
_MySecondPageState createState() => _MySecondPageState();
}

class _MySecondPageState extends State<MySecondPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("${widget.data.title}"),
),
body: Center(
child: Container(

child: Column(
children: <Widget>[
Text("Message: ${widget.data.message}",style: TextStyle(fontSize: 20),),
RaisedButton(
onPressed: () {
Navigator.pop(context,"I am coming from Second Activity");
},
child: Text("Go Back with Data"),
),
],
),
),
),
);
}
}

class Data{
String title;
String message;
Data(this.title,this.message);
}




Define Route in Flutter for Navigation of Screen





So far we go through the navigation using the navigator push method. It's good for less number of pages. Now, We will configure the route at one place and used it route the user to the respective screen. Let's explore how to define the named route and use it in the flutter.





Define the Named Route in Flutter





So we need to define the named route in the main section of the app as given below.





initialRoute: '/',
routes: {
'/':(context) => MyHomePage(title:'Home Page'),
'/page1': (context) => MyFirstPage(),
'/page2':(context) => MySecondPage(),
},




So initial route ('/') defined in the above example is the page which will be loaded by default. In other words, we can say that it is the home page of the application. The other page is conditional and navigates to screen based on input given by the navigator during the push.





Use the Named route to navigate





We need to use the navigator.pushnamed to show the respective page.





 Navigator.pushNamed(context,'/page1');




We have created three pages to demonstrate the navigation we have used the three page. HomePage, FirstPage, and Second Page.





On the HomePage, we have added two buttons to launch the respective Page1 and Page2.





Page Route in Navigation




Full Code of Above Example





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(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
backgroundColor: Colors.white,
accentColor: Colors.deepPurple,
buttonColor: Colors.blue,
buttonTheme: ButtonThemeData(textTheme: ButtonTextTheme.primary)
),
initialRoute: '/',
routes: {
'/':(context) => MyHomePage(title:'Home Page'),
'/page1': (context) => MyFirstPage(),
'/page2':(context) => MySecondPage(),
},
// home: MyHomePage(title: 'Flutter Page Navigation Demo'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key home, this.title}) : super(key: home);
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(onPressed: () {
Navigator.pushNamed(context,'/page1');
},
child: Text("Go to Page1",style: TextStyle(fontSize: 20),),
),
RaisedButton(onPressed: () {
Navigator.pushNamed(context,'/page2');
},
child: Text("Go to Page2",style: TextStyle(fontSize: 20),),

),
Text("Tab On above button to lauch the pages",style: TextStyle(fontSize: 20)),
],
),
),
);
}
}
class MyFirstPage extends StatefulWidget {
MyFirstPage({Key page1}) : super(key: page1);

@override
_MyFirstPageState createState() => _MyFirstPageState();
}

class _MyFirstPageState extends State<MyFirstPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("First Page"),
),
body: Center(

child: Container(

child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("This is the First Page",style: TextStyle(fontSize: 20),),
RaisedButton(
onPressed: () {
Navigator.pop(context,"I am coming from Second Page");
},
child: Text("Go Back to Home!",style: TextStyle(fontSize: 20),),
),
],
),
),
),
);
}
}

class MySecondPage extends StatefulWidget {
MySecondPage({Key key}) : super(key: key);

@override
_MySecondPageState createState() => _MySecondPageState();
}

class _MySecondPageState extends State<MySecondPage>{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Page"),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("This is the Second Page",style: TextStyle(fontSize: 20),),
RaisedButton(
onPressed: () {
Navigator.pop(context,"I am coming from Third Page3");
},
child: Text("Go Back to Home!",style: TextStyle(fontSize: 20),),
),
],
),
),
),
);
}
}




Wrapping Up





I hope you enjoyed the article. In this article, I tried to make you understand the logic of flutter by keeping things simple. We have created two pages one is the home page(Referred as First Page) and other is with the name of the second page. We have shown the three scenarios of navigation First Navigation without data, Send the data to the second page and Receive the data from second activity as a result, further, we have explored the navigation using the page route. You can explore more on flutter website.


Comments

Popular posts from this blog

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android
Just go to the android folder and open it in separate windows. We will have the following project structure.









Create the Activity Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.
Update the project build config …