i want to switch between screen in flutter, when i switch screen from main screen to second screen it work fine whenever i press back button from Second Screen the app become black and it show error message 5243 pos 12 history is not empty: is not true
import 'package:flutter/material.dart';
import 'second_screen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: null,
body: Padding(
padding: const EdgeInsets.only(
left: 12.0, top: 28.0, right: 12.0, bottom: 12.0),
child: SingleChildScrollView(
child: Column(
children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
InkWell(
onTap: (){
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) =>
const SecondScreen()));
},
child: Center(
child: Container(
margin: const
EdgeInsets.only(right:12.0),
height: 200,
width: 200,
color: Colors.deepOrange,
child: const Text('click me to jump'),
),
),
),
Container(
margin: const EdgeInsets.only(right: 12.0),
height: 200,
width: 200,
color: Colors.grey
),
],
),
),
],
),
),
),
);
}
}
and here is my second screen code
import 'package:flutter/material.dart';
class SecondScreen extends StatelessWidget{
const SecondScreen({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: _SecondScreen() ,
);
}
}
class _SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
return false;
} ,
child: Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: Center(
child: ElevatedButton(
child: const Text('Go back to First Screen'),
onPressed: () {
// Navigate back to the first screen
Navigator.pop(context);
},
),
),
),
); }
what i have done mistake any assist appreciated.
2
Answers
Remove your
MaterialApp
in second screen and use scaffold instead(you don’t need to use Material app in every screen, its a one time thing)
Update Your Code like this
you are using Navigator.pushReplacement
pushReplacement is used when you don’t need to back. it will remove all your previous routes.
try to use Navigator.push
-> Navigator.push used to keep you all previous routes.
example: