flutter 未处理异常:此小部件已被卸载,因此State不再具有上下文(并且应被视为已失效)

c2e8gylq  于 2023-04-13  发布在  Flutter
关注(0)|答案(2)|浏览(153)
@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,
    );
  }

我正在我的loadmore列表视图中执行搜索,当我从API中搜索数据时,这会导致错误。
错误:
未处理异常:此小部件已被卸载,因此State不再具有上下文(并且应被视为已失效)。E/flutter(21599):考虑在“dispose”期间取消任何活动的工作,或者使用“mounted”getter来确定State是否仍然是活动的。

new9mtju

new9mtju1#

可以在调用setState()之前检查mounted

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

布尔安装
此State对象当前是否在树中。
在创建State对象之后和调用initState之前,框架通过将State对象与BuildContext关联来“装载”该对象。State对象将保持装载状态,直到框架调用dispose,在此之后,框架将不再要求State对象再次生成。
除非mounted为true,否则调用setState是错误的。
https://api.flutter.dev/flutter/widgets/State/mounted.html

j0pj023g

j0pj023g2#

if(mounted)已弃用。您不能直接使用。

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

相关问题