Flutter: Navigator.pop() Is Not Working Properly In My Code
I have code below in flutter and when i press on back arrow button it crashes the app and white screen appear however in appears by default in other pages and i implemented it in other pages manually ... can someone please tell me what is the problem here cuz i couldn't figure it out?
thanks in advance
// ignore_for_file: avoid_function_literals_in_foreach_calls, prefer_const_constructors, prefer_const_literals_to_create_immutables, use_key_in_widget_constructors, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, sized_box_for_whitespace, deprecated_member_use, file_names
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
// ignore: unused_import
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
// ignore: unused_import
import 'package:localize_and_translate/localize_and_translate.dart';
import 'package:menu_app/About.dart';
void main() => runApp(HotDrinks());
class HotDrinks extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var screenHeight = MediaQuery.of(context).size.height;
var screenWidth = MediaQuery.of(context).size.width;
Future<List<Widget>> createList() async {
List<Widget> items = <Widget>[];
String dataString = await rootBundle
.loadString(translator.translate("assets/hotDrinks.json"));
List<dynamic> dataJSON = jsonDecode(dataString);
dataJSON.forEach((object) {
String finalString = "";
List<dynamic> dataList = object["placeItems"];
dataList.forEach((item) {
finalString = finalString + item + " | ";
});
items.add(Padding(
padding: EdgeInsets.all(2.0),
child: Container(
decoration: BoxDecoration(
color: Color.fromRGBO(255, 255, 255, 0.7),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [
BoxShadow(
color: Colors.black12,
spreadRadius: 2.0,
blurRadius: 5.0),
]),
margin: EdgeInsets.all(5.0),
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
ClipRRect(
child: Image.asset(
object["placeImage"],
fit: BoxFit.cover,
width: 280,
height: 180,
),
),
SizedBox(
width: 250,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
translator.translate(object["placeName"]),
style: GoogleFonts.elMessiri(
textStyle: TextStyle(
fontSize: 15.0, color: Colors.black54)),
),
Text(
translator.translate(" ${object["minOrder"]} IQD"),
style:
TextStyle(fontSize: 12.0, color: Colors.black54),
)
],
),
),
)
],
),
),
));
});
return items;
}
return Scaffold(
appBar: AppBar(
backgroundColor: HexColor("#242424"),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
iconSize: 20.0,
onPressed: () {
Navigator.pop(context); //not working
},
),
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
fit: BoxFit.contain,
height: 40,
),
],
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min, // set min
children: <Widget>[
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/backg.png"),
fit: BoxFit.cover,
),
),
height: 3000,
width: screenWidth,
child: FutureBuilder<List<Widget>>(
initialData: [Text("")],
future: createList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Text("Loading");
if (snapshot.hasError) {
return Text("Error ${snapshot.error}");
}
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(8.0),
child: GridView.count(
childAspectRatio: 1, // items' width/height
crossAxisCount: 2,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: [
// ignore: sdk_version_ui_as_code
...?snapshot.data,
],
));
} else {
return CircularProgressIndicator();
}
}),
)
],
),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
backgroundColor: Colors.black,
child: Icon(
MdiIcons.information,
color: Colors.white,
)),
);
}
}
Answer
It's because there's nothing "underneath" MyHomePage
.
Here's how routing works in Flutter - think of it as a stack of screens. The initial route (bottom of the stack) is the first screen you see when you open the app, in your case it's MyHomePage
. If you push a route on top of this screen, the old screen (MyHomePage
) is still there, but hidden underneath the new screen that you just pushed. So if you use pop()
in this new screen, it will kill it and take you back to the route that's underneath - MyHomePage
.
In your example, when you open the app, the home screen is MyHomePage
and there's nothing underneath, hence why there's nothing to display.
To visualise this, take a look at this video at the 11:00 mark.
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?