Navigator.pop shows me a black screen

Viewed 1179

It's been a while since I've been blocking backtracking on my flutter application, I tried the Navigator.pop (context) but I still ran into a black screen, I searched the forums for success but I'm still stuck. I want that when I click on return that it brings me back to my previous page without initializing the page

import 'package:MerchantIsland/log/database.dart';
import 'package:MerchantIsland/pages/home.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class productPage extends StatefulWidget {

final String productId;

const productPage({Key key, this.productId}) : super(key: key);
@override
_productPageState createState() => _productPageState();}

class _productPageState extends State<productPage> {


@override
Widget build(BuildContext context) {

ProductService productService = ProductService();

return WillPopScope(
  onWillPop: (){
    MovetoPreviousScreen();},
  child: Scaffold(
    appBar: AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back),
        onPressed: (){
          MovetoPreviousScreen();
          },
      ),
      centerTitle: true,
      title: Text(
        'Merchant island',
        style: TextStyle(
          fontSize: 20.0,
          fontWeight: FontWeight.bold,
        ),
      ),
    ),
    body: Stack(
      children: [
        FutureBuilder(
            future: productService.ProductData.doc(widget.productId).get(),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return Scaffold(
                  body: Center(
                    child: Text("Error: ${snapshot.error}"),
                  ),
                );
              }
              if(snapshot.connectionState==ConnectionState.done){
                Map<String, dynamic> documentData=snapshot.data.data();
                return ListView(
                  children: [
                    Container(
                      height: 400.0,
                      child: Image.network(
                        "${documentData['pictures'][0]}",
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4.0,horizontal: 24.0),
                      child: Text('${documentData['productName']}'??"Nom du produit",
                        style:TextStyle(
                          fontSize: 28.0,
                          fontWeight: FontWeight.bold,
                        ) ,),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4.0,horizontal: 24.0),
                      child: Text('${documentData['price']}',
                          style:TextStyle(
                              fontSize: 22.0,
                              fontWeight: FontWeight.bold,
                              color:Colors.red
                          ) ),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 4.0,horizontal: 24.0),
                      child: Text('${documentData['description']}',
                          style:TextStyle(
                              fontSize: 18
                          ) ),
                    )
                  ],
                );
              }
              return Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }),
      ],
    ),
  ),
); }

 // ignore: non_constant_identifier_names
 void MovetoPreviousScreen() {
   Navigator.of(context).pop();  }}

return page

 import 'package:MerchantIsland/log/database.dart';
 import 'package:MerchantIsland/log/loginUI.dart';
 import 'package:MerchantIsland/pages/Sellproduct.dart';
 import 'package:MerchantIsland/pages/bidPage.dart';
 import 'package:MerchantIsland/products/productPage.dart';
 import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:firebase_auth/firebase_auth.dart';
 import 'package:flutter/material.dart';
 import 'package:MerchantIsland/pages/profil.dart';
 import 'package:MerchantIsland/pages/balance.dart';
 import 'package:MerchantIsland/pages/Settings.dart';
 import 'package:google_sign_in/google_sign_in.dart';


 // ignore: camel_case_types
 class home extends StatefulWidget {
 @override
 _homeState createState() => _homeState();}

 // ignore: camel_case_types
 class _homeState extends State<home> {
 ProductService productService = ProductService();

 @override
 Widget build(BuildContext context) {

  return Scaffold(
  appBar: AppBar(
    centerTitle: false,
    title: Text("Merchant Island"),
    actions: [
      IconButton(
        icon: Icon(Icons.search, color: Colors.white,), onPressed: null,),
    ],
  ),
  body:  Stack(
    children: [
      FutureBuilder<QuerySnapshot>(
          future: productService.ProductData.get(),
          builder:(context,snapshot){
            if(snapshot.hasError){
              return Scaffold(
                body: Center(
                  child: Text("Error: ${snapshot.error}"),
                ),
              );
            }
            if(snapshot.connectionState==ConnectionState.done){
              return Container(
                child: ListView(
                  children: snapshot.data.docs.map((documents){
                    return Container(
                      child: GestureDetector(
                        onTap: (){
                          Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>productPage(productId: documents.id,)));
                        },
                        child: Container(
                          child: productCard(documents.data()["productName"],documents.data()["category"], documents.data()["price"],documents.data()["pictures"]) ,
                        ),
                      ),
                    );
                  }).toList(),
                ),
              );
            }
            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          }),
    ],
  ),
  drawer: BDrawer(context),
); }}

  // ignore: non_constant_identifier_names
  Drawer BDrawer(BuildContext context) {
  FirebaseAuth _auth = FirebaseAuth.instance;
  GoogleSignIn _googleSignIn = GoogleSignIn();

  Future <void> signOut() async {
await _auth.signOut();
await _googleSignIn.disconnect();
Navigator.of(context).push(
    MaterialPageRoute(builder: (context) => LoginUI()));}
return Drawer(
child: ListView(
    children: [

      UserAccountsDrawerHeader(
        accountName: Text('TITAN', style: TextStyle(
          fontSize: 18.0,
        ),),
        accountEmail: Text('philippetankoano@gmail.com'),
        currentAccountPicture: GestureDetector(
          child: CircleAvatar(
            backgroundColor: Colors.grey,
            child: Icon(
                Icons.person, color: Colors.white
            ),
          ),
        ),

        otherAccountsPictures: [
          InkWell(
            onTap: () =>
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (context) => profil(),)),
            child: (
                Icon(
                  Icons.mode_edit, size: 30.0,
                )
            ),
          )
        ],
      ),

      InkWell(
        onTap: () =>
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => balancepage())),
        child: ListTile(
          leading: Icon(
            Icons.account_balance, size: 30.0, color: Colors.blue,),
          title: Text(' Balance', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),

      InkWell(
        onTap: () =>
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => home())),
        child: ListTile(
          leading: Icon(Icons.home, size: 30.0, color: Colors.blue,),
          title: Text(' Home', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),
      InkWell(
        onTap: () =>
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => SellProduct())),
        child: ListTile(
          leading: Icon(
            Icons.account_balance, size: 30.0, color: Colors.blue,),
          title: Text(' Sell product', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),
      InkWell(
        onTap: () {},
        child: ListTile(
          leading: Icon(
            Icons.shopping_basket_outlined, size: 40.0,
            color: Colors.blue,),
          title: Text('Sale', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),


      InkWell(
        onTap: () {},
        child: ListTile(
          leading: Icon(Icons.category, size: 30.0, color: Colors.blue,),
          title: Text(' Categories', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),

      InkWell(
        onTap: () =>
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => bidPage())),
        child: ListTile(
          leading: Icon(
            Icons.event_available, size: 40.0, color: Colors.blue,),
          title: Text(' Bid', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),

      Divider(),

      InkWell(
        onTap: () =>
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => Settingpage(),)),
        child: ListTile(
          leading: Icon(Icons.settings, size: 30.0, color: Colors.blue,),
          title: Text(' Setting', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),
      InkWell(
        onTap: () {},
        child: ListTile(
          leading: Icon(Icons.help, size: 30.0, color: Colors.blue,),
          title: Text(' Help', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),
      InkWell(
        onTap: () async {
          signOut();
        },
        child: ListTile(
          leading: Icon(Icons.exit_to_app, size: 30.0, color: Colors.blue,),
          title: Text(' Deconnexion', style: TextStyle(
            fontSize: 18.0,
          ),),
        ),
      ),
    ]
), );}
 Padding productCard(String name,String category,String price,List imageUrl){
 return Padding(
 padding: const EdgeInsets.all(6.0),
 child: Container(
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(10.0),
    boxShadow: [
      BoxShadow(
          color: Colors.grey,
          offset: Offset(-2,-1),
          blurRadius: 5
      )
    ] ),
  child: GestureDetector(

  child: Column(
    children: [
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(7.0),
            child: Image.network(

              "${imageUrl[0]}",
              height: 500,
              width: 450,
            ),
          ),
        ],
      ),
      Padding(
          padding: const EdgeInsets.all(20.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(' $name ',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold)),
              Text('$price ',style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold,color: Colors.red)),

            ],
          ),
        ),
      Text('Categorie:     $category \n',style: TextStyle(fontSize: 24.0,)),
    ],
  ),
), ),);}
4 Answers

Method One(Recommended)

First check if there is more than one Material App in your project if found then remove all except the root one (Child of MyApp) if that does not work or you have only one MaterialApp in your project then only try second method

Method Two(Try only if method one doesn't solved your issue or you don't have more than one MaterialApp in your project)

Replace Navigator.of(context).pop(); with Navigator.of(context,rootNavigator:true).pop(context)

If you got a black screen, it's probably because you are popping the only screen in your stack.

If you want that Navigator.of(context).pop() remove only the last screen, you have to display the current screen with a Navigator.of(context).push()

When clicking on the custom back icon Leading with in flutter

Replace Navigator.of(context).pop(); with Navigator.of(context,rootNavigator:true).pop(context)

 appBar: AppBar(
        automaticallyImplyLeading: true,
        backgroundColor: ColorConstants.kBlackColor,
        leading: BackButton(
          color: ColorConstants.kWhiteColor,
          onPressed: (){
            Navigator.of(context,rootNavigator:true).pop(context);
          },
        ),
      ),

In my case the problem was having some Navigator.pop(context) inside other callback functions.

When I clicked the back button, a socket would close, and consequently call the callback function (that also called pop()), so I would have Navigator.pop(context) called more than one time. And since my Page widget was the second element of the stack, calling it 2 times would pop also the root, therefore generating the black screen.

What I did to fix it, even though I think there might be better solutions, was substituting all the Navigator.pop(context) calls with the following:

if (Navigator.canPop(context)) {
    Navigator.pop(context);
}

Another possible solution would be to initialize a bool variable (or a some kind of counter) and then call pop() only if that variable is true, then set it to false.:

// init
bool variable = true;

if (variable) {
    Navigator.pop(context);
    variable = false;
}
Related