This widget has been unmounted, so the State no longer has a context (and should be considered defunct)

Viewed 1200

I woke up this morning tried to make some changes to my orders.dart model. And then after that i tried to refresh my flutter app and i got this error:

I/ProviderInstaller( 6182): Installed default security provider GmsCore_OpenSSL
E/flutter ( 6182): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 6182): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
E/flutter ( 6182): #0      State.context.<anonymous closure>
package:flutter/…/widgets/framework.dart:1088
E/flutter ( 6182): #1      State.context
package:flutter/…/widgets/framework.dart:1094
E/flutter ( 6182): #2      _SplashScreenState.initState.<anonymous closure>
package:splashscreen/splashscreen.dart:165

Here is my orders.dart file:

class Order{
  final String oid;
  final String item;
  final String receiver_nrc;
  final String description;
  final String amount;
  final String seller;
  final String seller_location;
  final DateTime pickup_date;
  final DateTime delivery_date;
  final String scanned_document;
  final String order_status;
  final String payment_status;

  Order({this.item, this.receiver_nrc, this.description, this.amount, this. seller,this.seller_location,  this.pickup_date, this.delivery_date, this.scanned_document, this.order_status, this.payment_status, this.oid}); 
}

My slash_screen.dart file:

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:merza/screens/home/home.dart';
import 'package:merza/screens/home/orders/order_details.dart';
import 'package:merza/screens/home/staff/staff_home.dart';
import 'package:merza/screens/wrapper.dart';
import 'package:splashscreen/splashscreen.dart';


class SplashScreenCustom extends StatefulWidget {
  @override
  _SplashScreenCustomState createState() => new _SplashScreenCustomState();
}

class _SplashScreenCustomState extends State<SplashScreenCustom> {
  @override
  Widget build(BuildContext context) {
    return new SplashScreen(
      seconds: 14,
      navigateAfterSeconds: new Wrapper(),
      title: new Text('Promoting safe transactions in digital trade!',
      style: new TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 20.0
      ),),
      image: new Image.network('https://madvertadvertising.com/media/merza_splash.jpeg'),
      backgroundColor: Colors.white,
      styleTextUnderTheLoader: new TextStyle(),
      photoSize: 100.0,
      onClick: ()=>print("Flutter Egypt"),
      loaderColor: Colors.red
    );
  }
}


//Loading screen


class LoadingScreenCustom extends StatefulWidget {
  final  dynamic page;
  LoadingScreenCustom({this.page});
  @override
  _LoadingScreenCustomState createState() => new _LoadingScreenCustomState();
}

class _LoadingScreenCustomState extends State<LoadingScreenCustom> {
  dynamic page = Home();
  @override
  Widget build(BuildContext context) {
    if (widget.page == 'home') {
      page = Home();
      
    }
    if (widget.page == 'staff_home') {
      page = StaffHome();
      
    }
    if (widget.page == 'order_details') {
      page = OrderDetails();
      
    }

    
    return new SplashScreen(
      seconds: 2,
      navigateAfterSeconds:  page,
      title: new Text('Loading, please wait..',
      style: new TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 20.0
      ),),
      image: new Image.network('https://madvertadvertising.com/media/merza_splash.jpeg'),
      backgroundColor: Colors.white,
      styleTextUnderTheLoader: new TextStyle(),
      photoSize: 100.0,
      onClick: ()=>print("Flutter Egypt"),
      loaderColor: Colors.red
    );
  }
}

//Spinkit loading screen

class LoadingSpin extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green[100],
      child: Center(
        child: SpinKitChasingDots(
          color: Colors.green,
          size: 50.0,
        ),
      ),
    );
  }
}

And here is my home.dart file where the error is coming from:

import 'package:flutter/material.dart';
import 'package:merza/models/orders.dart';
import 'package:merza/models/user.dart';
import 'package:merza/screens/home/items.dart';
import 'package:merza/screens/home/orders/delivered_order.dart';
import 'package:merza/screens/home/orders/order_status.dart';
import 'package:merza/screens/user/add_order.dart';
import 'package:merza/services/auth.dart';
import 'package:merza/services/databse.dart';
import 'package:merza/shared/grid.dart';
import 'package:intl/intl.dart';
import 'package:merza/shared/menus.dart';
import 'package:merza/shared/splash_screen.dart';
import 'package:provider/provider.dart';
import 'package:merza/screens/home/orders/orders_list.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import 'orders/orders_tile.dart';
class Home extends StatelessWidget {
//Auth
  AuthService _auth = AuthService();

 //Database 
 Database _db = Database();
 
  @override
  
  Widget build(BuildContext context) {

   final user = Provider.of<User>(context);
   
  if(user.uid == null){
     Navigator.pushNamedAndRemoveUntil(context, "/home", (r) => false);

   }else{
   
    return StreamBuilder<UserData>(
      
      stream: Database(uid: user.uid).userData,
      builder: (context, snapshot) {
        
      if (snapshot.hasData) {
        UserData userData = snapshot.data;
        
      //Streambuilder for delivered orders
        return StreamBuilder<List<Order>>(
          stream: Database(receiver_nrc: userData.nrc, paramOne: 'payment_status', paramValue: 'unpaid').dataFetch,
          builder: (context, snapshot2) {
            
            if (snapshot2.hasData) {
              String count_unpaid =  snapshot2.data.length.toString();
            return StreamBuilder <List<Order>>(
              stream:  Database(receiver_nrc: userData.nrc, paramOne: 'order_status', paramValue: 'delivered').dataFetch,
              builder: (context, snapshot3) {
                
                if (snapshot3.hasData) {
                  String count_awaiting =  snapshot3.data.length.toString();
                return StreamProvider<List<Order>>.value(
                  value: Database(receiver_nrc: userData.nrc).orders,
                    
                    child: Scaffold(
                    appBar: LoggedBar(title: 'Merza',),

                    body: SingleChildScrollView(
                            child: Column(
                        children: [

                          
                       
                       Container(),   // Required some widget in between to float AppBar

        Container(    // To take AppBar Size only
          
          child: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.white,
            leading: IconButton(icon: Icon(Icons.home), color: Colors.green[900], onPressed: (){
              Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
            },),
            primary: false,
            title: TextField(
                decoration: InputDecoration(
                    hintText: "Search",
                    border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.green[900]))),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.search, color: Colors.green[900]), onPressed: () {},),
             
            ],
          ),
        ),
                          Container(
                            color: Colors.green,
                            padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                         child: Text('A TRADING ZONE THAT PROMOTES SAFETY TRADING AND SECURE DIGITAL TRANSACTIONS', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.white)),
                         
                         ), Container(
                            margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                            child: Row(

                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [

                                Expanded(
                                  child: Card(
                                    
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                         Container(
                                              width: 130,
                                              child: ListTile(

                                              title: Image.network('https://madvertadvertising.com/media/merza/images/seller.jpeg'),
                                              onTap: (){
                                           // Navigator.push(context, MaterialPageRoute(builder: (context) => ItemsPage()));
                                          },
                                          ),
                                            ),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            
                                           
                                            const SizedBox(width: 8),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Card(
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                              Container(
                                              width: 130,
                                              child: ListTile(

                                              title: Image.network('https://madvertadvertising.com/media/merza/images/delivery.jpeg'),
                                              onTap: (){
                                             Navigator.push(context, MaterialPageRoute(builder: (context) => AwaitingOrdersList(nrc: userData.nrc, paramValueOne: 'order_status', paramValueTwo: 'delivered', barTitle: 'Delivered', isStaff: userData.is_staff.toString(), allowStaffPrivaledges: 'no',)));
                                          },
                                          ),
                                            ),
                                        
                                            const SizedBox(width: 8),
                                          
                                        
                                      ],
                                    ),
                                  ),
                                ),


                              ],
                            ),

                          ),


                          Container(
                            margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                            child: Row(

                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [

                                Expanded(
                                  child: Card(
                                    
                                    child: Column(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                         Container(
                                              width: 130,
                                              child: ListTile(

                                              title: Image.network('https://madvertadvertising.com/media/merza/images/items.jpeg'),
                                              onTap: (){
                                            Navigator.push(context, MaterialPageRoute(builder: (context) => ItemsPage()));
                                          },
                                          ),
                                            ),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            
                                           
                                            const SizedBox(width: 8),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: Container(
                                    child: Card(
                                      child: Column(
                                        
                                        mainAxisSize: MainAxisSize.min,
                                        children: <Widget>[
                                            Container(
                                              width: 130,
                                              child: ListTile(

                                              title: Image.network('https://madvertadvertising.com/media/merza/images/payment.jpeg'),
                                          
                                          onTap: (){
                                             Navigator.push(context, MaterialPageRoute(builder: (context) => DeliverdordersList(nrc: userData.nrc, paramValueOne: 'payment_status', paramValueTwo: 'paid', barTitle: 'Paid orders',)));
                                          }
                                          ,
                                          ),
                                            ),
                                          
                                              const SizedBox(width: 8),
                                            
                                          
                                        ],
                                      ),
                                    ),
                                  ),
                                ),


                              ],
                            ),

                          ),
                          Text('My recent placed orders', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
                        
                        Container(
                          child: OrdersList(),
                          ),
                       
                       SizedBox(height: 10.0),
                       
                        ],
                        
                        
                      ),
                    ),
                    



                    drawer: DrawerLogged()

                  ),
                );
                }else{
                  return LoadingScreenCustom(page:'home');
                }
              }
            );
            }else{
               return LoadingScreenCustom(page:'home');
            }
          }
        );
      }else{
        return LoadingScreenCustom(page:'home');
      }
      }
    );
  }
  }
}

I have tried to look for a solution on Google but all in vain. Please help because this is my final part of the project.

1 Answers

You can check if the widget is mounted before calling setState():

if (mounted) {
  setState(() => {});
}

It was also possible that you should check your Navigator and context.

Related