Необработанное исключение: Этот виджет был отключен, поэтому состояние больше не имеет контекста (и его следует считать несуществующим).

#flutter #dart

Вопрос:

  @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 amp;amp; 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,
    );
  }
 

Я реализую поиск в своем представлении списка loadmore, что вызывает ошибку при поиске данных из API.

Ошибка:

Необработанное исключение: Этот виджет был отключен, поэтому состояние больше не имеет контекста (и его следует считать несуществующим). E/flutter (21599): Рассмотрите возможность отмены любой активной работы во время «удаления» или использования «смонтированного» геттера, чтобы определить, все еще ли состояние активно.

Ответ №1:

вы можете проверить наличие смонтированного перед вызовом setState()

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

бул смонтирован

Находится ли этот объект состояния в настоящее время в дереве.

После создания объекта состояния и перед вызовом initState платформа «монтирует» объект состояния, связывая его с BuildContext. Объект состояния остается смонтированным до тех пор, пока фреймворк не вызовет dispose, после чего фреймворк никогда не попросит объект состояния построить снова.

Вызов setState является ошибкой, если значение смонтировано не равно true.

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

Комментарии:

1. в чем смысл этого я не понял

2. как я понял из вашего ответа, я должен проверить, правильно ли(смонтировано), затем я должен вызвать setState?

3. @Vishali да точно

4. Я видел ваш код, но вы не использовали if (смонтированный) перед вызовом setState, exmaple : вам нужно сделать это, если(смонтировано) { setState (() { SearchResult.addAll(значение.данные); _totalRecords = значение.recordsTotal; });}