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

  1. You have Shared great content here about Software Testing Course For Beginners Online..... I am glad to discover this post as I found lots of valuable data in your article. Thanks for sharing an article like this.

    ReplyDelete

Post a Comment

Popular posts from this blog

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 s...

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface ...

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t...