Navigate to a new Screen and Back and Pass Data

 import "package:flutter/material.dart";


void main()
{
runApp(const MyApp());
}
class MyApp extends StatelessWidget
{
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "CounterApp",
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.grey,
),
home: CounterApp(),
);
}
}
class CounterApp extends StatefulWidget
{
const CounterApp({super.key});
@override
State<CounterApp> createState()
{
return CounterAppState();
}
}
class CounterAppState extends State<CounterApp>
{
var counter = 0;

void increment()
{
setState(() {
counter++;
},);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Counter App"),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("$counter",
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 50.0),),
const SizedBox(height: 30.0),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return NextScreen(index: counter);
},
),
);
},
style: ElevatedButton.styleFrom(
fixedSize: const Size(350.0,50.0),
backgroundColor: Colors.blue,
),
child: const Text("Go to next screen",
style: TextStyle(fontSize: 30.0, color: Colors.white),),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
increment();
},);
},
backgroundColor: Colors.blue,
child: const Icon(Icons.add, color: Colors.white),
),
);
}
}
class NextScreen extends StatelessWidget
{
NextScreen({super.key, required this.index});
int index;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("This is Next Screen"),
centerTitle: true,
backgroundColor: Colors.grey,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("$index", style: const TextStyle(fontSize: 50.0, fontWeight: FontWeight.bold),),
const SizedBox(height: 30.0),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
style: ElevatedButton.styleFrom(
fixedSize: const Size(350.0, 50.0),
backgroundColor: Colors.blue,
),
child: const Text("Go back",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 30.0, color: Colors.white),),
),
],
),
),
);
}
}

Comments

Popular posts from this blog

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter