Vishali
Vishali

Reputation: 1397

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

 @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() async {
    await StorageUtil.getInstance();
    String cookie = StorageUtil.getString('sess');
    String page = currentPage.toString();

    if (cookie != null) {
      ApiService.getEstimateList(cookie, page, myAllestimate, search)
          .then((value) {
        if (value.data != null) {
          if (count < _totalRecords) {
            setState(() {
              invoicelist.addAll(value.data);
              print(value.data);
              _totalRecords = value.recordsTotal;
            });
            print(
                'List size is $count and TotalRecord - ${value.recordsTotal} , TotalFiltered - ${value.recordsFiltered}');
          }
        }
      });
    }
  }

  Future<bool> _loadMoreData() async {
    print('_loadMoreData()');
    await Future.delayed(Duration(seconds: 0, milliseconds: 1000));
    currentPage += 1;
    _loadData();
    return true;
  }

  Future<void> _refresh() async {
    currentPage = 1;
    _totalRecords = 100;
    invoicelist.clear();
    _loadData();
  }

 getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
    // dateFormat = 'MM/dd/yy';
    final DateTime docDateTime = DateTime.parse(givenDateTime);
    return DateFormat(dateFormat).format(docDateTime);
  }

  onSearchTextChanged(String text) async {
    String search = text.toLowerCase();
    searchResult.clear();
    if (text.isEmpty) {
      setState(() {});
      return;
    }
    if (_selectedIndex == 0) {
      myAllestimate = 'my';
    } else {
      myAllestimate = 'all';
    }
    currentPage = 1;
    String cookie = StorageUtil.getString('sess');
    String page = currentPage.toString();

    if (cookie != null) {
      ApiService.getEstimateList(cookie, page, myAllestimate, search)
          .then((value) {
        if (value.data.length > 0) {
          if (count < _totalRecords) {
            setState(() {
              searchResult.addAll(value.data);
              _totalRecords = value.recordsTotal;
            });
            print(
                'searchResult size is $count and TotalRecord - ${value.recordsTotal} , TotalFiltered - ${value.recordsFiltered}');
          }
        } else {
          searchResult.clear();
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
                context,
                new MaterialPageRoute(
                    builder: (context) =>
                        new CatalogService(pageDirection: pageDirection)));
          },
          backgroundColor: Colors.orange[600],
          elevation: 2.0,
          child: Icon(
            Icons.add,
            color: Colors.white,
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        bottomNavigationBar: _bottomTab(),
        appBar: new AppBar(
          title: appBarTitle,
          actions: [
            new IconButton(
              icon: actionIcon,
              onPressed: () {
                setState(() {
                  if (this.actionIcon.icon == Icons.search) {
                    this.actionIcon = new Icon(Icons.close);
                    this.appBarTitle = new TextField(
                      controller: controller,
                      onChanged: onSearchTextChanged,
                      style: new TextStyle(
                        color: Colors.white,
                      ),
                      decoration: new InputDecoration(
                          prefixIcon:
                              new Icon(Icons.search, color: Colors.white),
                          hintText: "Search...",
                          hintStyle: new TextStyle(color: Colors.white)),
                    );
                  } else {
                    controller.clear();
                    searchResult.clear();
                    this.actionIcon = new Icon(Icons.search);
                    this.appBarTitle = new Text("Manage Estimate");
                  }
                });
              },
            ),
          ],
        ),
        body: Stack(
          children: [
            Center(
              child: Visibility(
                visible: (search.length > 0 && searchResult.length > 0)
                    ? true
                    : false,
                child: Text('No Data Found'),
              ),
            ),
            Container(
                child: searchResult.length != 0 || controller.text.isNotEmpty
                    ? searchResults()
                    : buildResults()),
          ],
        ));
  }

  Widget searchResults() {
    return RefreshIndicator(
      child: LoadMore(
        isFinish: count >= _totalRecords,
        onLoadMore: _loadMoreData,
        child: ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            final item = searchResult[index];
            String date = item.invDate.toString();
            String strDate = getCustomFormattedDateTime(date, 'dd-MM-yyyy');
            return Container(
              padding: EdgeInsets.only(
                  top: 10.0, left: 20.0, right: 20.0, bottom: 10.0),
              child: GestureDetector(
                onTap: () {
                  print(searchResult[index].id);
                  String bmaster = StorageUtil.getString('bmaster');
                  String cookie = StorageUtil.getString('sess');
                  String id = searchResult[index].id.toString();
                  String mobile = searchResult[index].mobile.toString();
                  int custId = invoicelist[index].custId;

                  var weburl = '', pdfUrl;
                  ApiService.viewInvoice(cookie, id, bmaster, 'estimate')
                      .then((value) {
                    if (value != null) {
                      var result = jsonDecode(value);
                      if (result['status'].toString() == '1') {
                        var decode = Uri.decodeFull(result['url']);
                        var pdf_url = Uri.decodeFull(result['pdf_url']);
                        pdfUrl = pdf_url.toString();
                        weburl = decode.toString();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => WebViewContainer(
                                weburl, 'Estimate', pdfUrl, mobile, id, custId),
                          ),
                        );
                      }
                    }
                  });
                },
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setSp(150),
                              child: Text(
                                item.custName,
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.black,
                                  fontFamily: 'montserratbold',
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),

                            Padding(
                                padding:
                                    EdgeInsets.only(top: 2.0, bottom: 2.0)),
                            Text(
                              "EST-" + item.invNumber,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            Padding(padding: EdgeInsets.only(top: 2.0)),
                            Text(
                              strDate,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            // Padding(padding: EdgeInsets.only(top: 2.0)),
                            // Text(
                            //   'Party Balance-' +
                            //       item.p.toString(),
                            //   style: TextStyle(
                            //       fontSize: 12.0, color: Colors.black),
                            // ),
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text(
                              'Rs.' + item.totalAmt,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            Padding(padding: EdgeInsets.only(top: 10.0)),
                            Container(
                              width: ScreenUtil().setSp(100),
                              height: ScreenUtil().setSp(25),
                              decoration: BoxDecoration(
                                  color:
                                      Color(0xffffcdd2), // border: Border.all(
                                  //   color: Colors.red[500],
                                  // ),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(5))),
                              child: Container(
                                alignment: Alignment.center,
                                child: Text(
                                  (item.status == 0) ? 'Paid' : 'Not Paid',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'montserrat',
                                      fontSize: ScreenUtil().setSp(12),
                                      color: Colors.red),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Padding(padding: EdgeInsets.only(top: 15)),
                    Container(
                      margin: EdgeInsets.only(top: 5, bottom: 5),
                      child: const Divider(
                        height: 2,
                        thickness: 1,
                      ),
                    ),
                    // Text(item.custName),
                  ],
                ),
              ),
            );
          },
          itemCount: searchResult.length,
        ),
        whenEmptyLoad: true,
        delegate: DefaultLoadMoreDelegate(),
        textBuilder: DefaultLoadMoreTextBuilder.english,
      ),
      onRefresh: _refresh,
    );
  }

  Widget buildResults() {
    return RefreshIndicator(
      child: LoadMore(
        isFinish: count >= _totalRecords,
        onLoadMore: _loadMoreData,
        child: ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            final item = invoicelist[index];
            String date = item.invDate.toString();
            String strDate = getCustomFormattedDateTime(date, 'dd-MM-yyyy');
            return Container(
              padding: EdgeInsets.only(
                  top: 10.0, left: 20.0, right: 20.0, bottom: 10.0),
              child: GestureDetector(
                onTap: () {
                  print(invoicelist[index].id);
                  String bmaster = StorageUtil.getString('bmaster');
                  String cookie = StorageUtil.getString('sess');
                  String id = invoicelist[index].id.toString();
                  String estNumber = invoicelist[index].invNumber.toString();

                  String mobile = invoicelist[index].mobile.toString();
                  int custId = invoicelist[index].custId;

                  var weburl = '', pdfUrl;
                  ApiService.viewInvoice(cookie, id, bmaster, 'estimate')
                      .then((value) {
                    if (value != null) {
                      var result = jsonDecode(value);
                      if (result['status'].toString() == '1') {
                        var decode = Uri.decodeFull(result['url']);
                        var pdf_url = Uri.decodeFull(result['pdf_url']);
                        pdfUrl = pdf_url.toString();
                        weburl = decode.toString();
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => WebViewContainer(weburl,
                                'Estimate', pdfUrl, mobile, estNumber, custId),
                          ),
                        );
                      }
                    }
                  });
                },
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setSp(150),
                              child: Text(
                                item.custName,
                                style: TextStyle(
                                  fontSize: 14.0,
                                  color: Colors.black,
                                  fontFamily: 'montserratbold',
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),

                            Padding(
                                padding:
                                    EdgeInsets.only(top: 2.0, bottom: 2.0)),
                            Text(
                              "EST-" + item.invNumber,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            Padding(padding: EdgeInsets.only(top: 2.0)),
                            Text(
                              strDate,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            // Padding(padding: EdgeInsets.only(top: 2.0)),
                            // Text(
                            //   'Party Balance-' +
                            //       item.p.toString(),
                            //   style: TextStyle(
                            //       fontSize: 12.0, color: Colors.black),
                            // ),
                          ],
                        ),
                        Column(
                          children: <Widget>[
                            Text(
                              'Rs.' + item.totalAmt,
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(12.0),
                                  fontFamily: 'montserrat',
                                  color: Colors.black),
                            ),
                            Padding(padding: EdgeInsets.only(top: 10.0)),
                            Container(
                              width: ScreenUtil().setSp(100),
                              height: ScreenUtil().setSp(25),
                              decoration: BoxDecoration(
                                  color:
                                      Color(0xffffcdd2), // border: Border.all(
                                  //   color: Colors.red[500],
                                  // ),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(5))),
                              child: Container(
                                alignment: Alignment.center,
                                child: Text(
                                  'Not Paid',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontFamily: 'montserrat',
                                      fontSize: ScreenUtil().setSp(12),
                                      color: Colors.red),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    Padding(padding: EdgeInsets.only(top: 15)),
                    Container(
                      margin: EdgeInsets.only(top: 5, bottom: 5),
                      child: const Divider(
                        height: 2,
                        thickness: 1,
                      ),
                    ),
                    // Text(item.custName),
                  ],
                ),
              ),
            );
          },
          itemCount: count,
        ),
        whenEmptyLoad: true,
        delegate: DefaultLoadMoreDelegate(),
        textBuilder: DefaultLoadMoreTextBuilder.english,
      ),
      onRefresh: _refresh,
    );
  }

I am implementing search in my loadmore listview which is causing error when I am searching data from API.

Error:

Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct). E/flutter (21599): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

Upvotes: 4

Views: 11179

Answers (2)

if(mounted) is deprecated. You can't use directly.

SchedulerBinding.instance?.addPostFrameCallback((_) {
  if (mounted) {
    // Perform updates to the UI
  }
});

Upvotes: 2

Hossam
Hossam

Reputation: 158

you can check for mounted before call setState()

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

bool mounted

Whether this State object is currently in a tree.

After creating a State object and before calling initState, the framework "mounts" the State object by associating it with a BuildContext. The State object remains mounted until the framework calls dispose, after which time the framework will never ask the State object to build again.

It is an error to call setState unless mounted is true.

https://api.flutter.dev/flutter/widgets/State/mounted.html

Upvotes: 6

Related Questions