Flutter 错误(在dispose()之后调用setState():(生命周期状态:不存在,未装入)

Flutter 错误(在dispose()之后调用setState():(生命周期状态:不存在,未装入),flutter,dart,Flutter,Dart,错误被抛出到两个区域(并且应用程序冻结)(当应用程序最小化时,当单击phones back按钮时,或者当另一个应用程序在颤振应用程序上运行时)。颤振版本:1.20.2(以前的版本没有此问题):两个功能是: @override void initState() { super.initState(); getItems(); } getItems() async { initClearVisibility(); initFilters(); setState(() { loadingI

错误被抛出到两个区域(并且应用程序冻结)(当应用程序最小化时,当单击phones back按钮时,或者当另一个应用程序在颤振应用程序上运行时)。颤振版本:1.20.2(以前的版本没有此问题):两个功能是:

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

getItems() async {
 initClearVisibility();
 initFilters();
 setState(() {
 loadingItems = true;
 Visibility(visible: true, child: CircularProgressIndicator());
 });

QuerySnapshot querySnapshot = await query.get();
 items = querySnapshot.docs;
 lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
 setState(() {
 loadingItems = false;
 Visibility(visible: false, child: CircularProgressIndicator());
 });
}

initClearVisibility() {
 if (Str.filterSelectCategory != Str.CATEGORY) {
  clearCategoryVisible = true;
  allCategoriesVisible = false;
   categoryValue = Str.filterSelectCategory;
  setState(() {});
 }
}

initFilters() async {   
 filterDefaultItems();
}

filterDefaultItems() async {
  query = _firestore
  .collection(Str.ITEMS)
  .where(Str.IS_ITEM_SOLD, isEqualTo: false) 
  .where(Str.ADDRESS, isEqualTo: userAddress1)
  //.orderBy(Str.DATE_POSTED)
  .limit(perPage);
}
第二个区域是下面的代码,我也得到了:

class FABBottomAppBarItem {
FABBottomAppBarItem({this.iconData, this.itemColor}); //, this.text});
IconData iconData;
var itemColor;
//String text;
}

class FABBottomAppBar extends StatefulWidget {
 FABBottomAppBar({
 this.items,
 this.centerItemText,
 this.height: 65.0,
 this.iconSize: 24.0,
 this.backgroundColor,
 this.color,
 this.selectedColor,
 this.notchedShape,
 this.onTabSelected,
 }) {
 assert(this.items.length == 2 || this.items.length == 4);
}
final List<FABBottomAppBarItem> items;
final String centerItemText;
final double height;
final double iconSize;
final Color backgroundColor;
final Color color;
final Color selectedColor;
final NotchedShape notchedShape;
final ValueChanged<int> onTabSelected;

@override
State<StatefulWidget> createState() => FABBottomAppBarState();
}

class FABBottomAppBarState extends State<FABBottomAppBar> {
//int _selectedIndex = 0;
int unreadCount = 0;

_updateIndex(int index) {
 widget.onTabSelected(index);
 setState(() {
  //_selectedIndex = index;
  });
}

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

@override
Widget build(BuildContext context) {
List<Widget> items = List.generate(widget.items.length, (int index) {
  return _buildTabItem(
    item: widget.items[index],
    index: index,
    onPressed: _updateIndex,
  );
});
items.insert(items.length >> 1, _buildMiddleTabItem());

return BottomAppBar(
  shape: widget.notchedShape,
  child: Row(
    mainAxisSize: MainAxisSize.max,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: items,
  ),
  color: widget.backgroundColor,
 );
}

Widget _buildMiddleTabItem() {
 return Expanded(
  child: SizedBox(
    height: MediaQuery.of(context).size.height * 0.075, //widget.height,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        SizedBox(
          height: MediaQuery.of(context).size.height * 0.04,
        ), 
        Text(
          widget.centerItemText ?? '',
          style: TextStyle(
              color: BwerereTheme.bwerereRed,
              fontSize: 14.0,
              fontWeight: FontWeight.w900),
        ),
      ],
    ),
  ),
  );
}

Widget _buildTabItem({
 FABBottomAppBarItem item,
 int index,
 ValueChanged<int> onPressed,
 }) 
{
 return Expanded(
  child: SizedBox(
    height: MediaQuery.of(context).size.height * 0.065,
    child: Material(
      type: MaterialType.transparency,
      child: InkWell(
        onTap: () => onPressed(index),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Stack(
              children: <Widget>[
                Icon(item.iconData,
                    color: item.itemColor,
                    size: IconTheme.of(context).size * 1.2),
                index == 2 ? badge() : Container()
              ],
            )
          ],
        ),
      ),
    ),
   ),
   );
  }

  Widget badge() => unreadCount < 1
   ? Container()
    : Container(
      padding: EdgeInsets.all(4.0),
      decoration: BoxDecoration(
          color: BwerereTheme.bwerereRed, shape: BoxShape.circle),
      child: Center(
        child: RobotoFont(
            text: "$unreadCount",
            textSize: 12.0,
            textColor: Colors.white,
            fontWeight: FontWeight.w400),
      ));

 void countDocuments() async {
 final uid = await FetchUserData().getCurrentUserID();
 QuerySnapshot _myDoc = await FirebaseFirestore.instance
    .collection("userUnreadMessages")
    .doc(uid)
    .collection(Str.MESSAGE_COLLECTION)
    .get();
 List<DocumentSnapshot> _myDocCount = _myDoc.docs;
 setState(() {
  unreadCount = _myDocCount.length;
  print('NOTIY LENGTH::: $unreadCount');
 });
}
class-appbarItem{
FABBottomAppBarItem({this.iconda,this.itemColor});/,this.text});
Iconda Iconda;
颜色变量;
//字符串文本;
}
类FABBottomAppBar扩展StatefulWidget{
法伯塔帕巴({
这个项目,,
此.centerItemText,
此高度:65.0,
此.i目录:24.0,
这个背景色,
这个颜色,
这是我选择的颜色,
这个缺口形状,
这次选举,
}) {
断言(this.items.length==2 | | this.items.length==4);
}
最后清单项目;
最终字符串centerItemText;
最终双倍高度;
最终的双重认知;
最终颜色背景色;
最终颜色;
最终颜色选择颜色;
最终缺口形状缺口形状;
最终价值已更改或未选定;
@凌驾
State createState()=>FABBottomAppBarState();
}
类AppBarState扩展了状态{
//int _selectedIndex=0;
int unreadCount=0;
_更新索引(整数索引){
已选择的控件(索引);
设置状态(){
//_selectedIndex=索引;
});
}
@凌驾
void initState(){
super.initState();
countDocuments();
}
@凌驾
小部件构建(构建上下文){
List items=List.generate(widget.items.length,(int索引){
return\u buildTabItem(
item:widget.items[索引],
索引:索引,,
onPressed:\u updateIndex,
);
});
items.insert(items.length>>1,_buildMiddleTabItem());
返回底部AppBar(
形状:widget.notchdshape,
孩子:排(
mainAxisSize:mainAxisSize.max,
mainAxisAlignment:mainAxisAlignment.spaceAround,
儿童:项目,
),
颜色:widget.backgroundColor,
);
}
小部件_buildMiddleTabItem(){
扩大回报(
孩子:大小盒子(
高度:MediaQuery.of(context).size.height*0.075,//widget.height,
子:列(
mainAxisSize:mainAxisSize.min,
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
大小盒子(
高度:MediaQuery.of(上下文).size.height*0.04,
), 
正文(
widget.centerItemText???“”,
样式:TextStyle(
颜色:BwerereTheme.bwerereRed,
字体大小:14.0,
fontWeight:fontWeight.w900),
),
],
),
),
);
}
Widget\u buildTabItem({
FabboutAppBarItem项目,
整数索引,
按下时更改值,
}) 
{
扩大回报(
孩子:大小盒子(
高度:MediaQuery.of(context).size.height*0.065,
儿童:材料(
类型:MaterialType.transparency,
孩子:InkWell(
onTap:()=>onPressed(索引),
子:列(
mainAxisSize:mainAxisSize.min,
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
堆叠(
儿童:[
图标(item.iconda,
颜色:item.itemColor,
大小:上下文的IconTheme.大小*1.2),
索引==2?徽章():容器()
],
)
],
),
),
),
),
);
}
Widget badge()=>unreadCount<1
?容器()
:容器(
填充:所有边缘设置(4.0),
装饰:盒子装饰(
颜色:bweretheme.bweretheme,形状:BoxShape.circle),
儿童:中心(
孩子:机器人字体(
文本:“$unreadCount”,
文本大小:12.0,
textColor:Colors.white,
fontWeight:fontWeight.w400),
));
void countDocuments()异步{
final uid=wait FetchUserData().getCurrentUserID();
QuerySnapshot\u myDoc=等待FirebaseFirestore.instance
.collection(“userUnreadMessages”)
.doc(uid)
.collection(Str.MESSAGE_collection)
.get();
列表_myDocCount=_myDoc.docs;
设置状态(){
unreadCount=\u myDocCount.length;
打印('NOTIY长度::$unreadCount');
});
}
}

FABBottomAppBarState的FRAMEWORK.DART中的错误

主页上的getItems()上引发了相同的错误

发生异常。 错误(在dispose()之后调用setState():FABBottomAppBarState#250ac(生命周期状态:已失效,未装入) 如果对不再出现在窗口小部件树中的窗口小部件(例如,其父窗口小部件的构建中不再包含该窗口小部件)的状态对象调用setState(),则会发生此错误。当代码从计时器或动画回调调用setState()时,会发生此错误。 首选的解决方案是取消计时器或停止在dispose()回调中侦听动画。另一种解决方案是在调用setState()之前检查此对象的“mounted”属性,以确保该对象仍在树中。 如果SETSTATE()被调用,则此错误可能指示内存泄漏,因为另一个对象在从树中移除该状态对象之后保留对该状态对象的引用。为了避免内存泄漏,请考虑在处理()期间中断对该对象的引用。 进一步的调查显示,这款应用程序需要大约400MB的内存(Ram),我觉得这太高了

帮助解决这个问题真的很有帮助。提前谢谢

其他信息: 在android 7.0、Flatter 1.20.2上运行时出错。请参阅上的类似/相关问题。请注意,我升级到Flatter 1.20.2并降级到1.7.5将需要在升级后进行大量更改,尤其是在Firestore上(注意:最近已更新)。

您可以使用:

  if (this.mounted) { // check whether the state object is in tree
    setState(() {
      // make changes here
    });
  }
mounted
检查此
状态
对象当前是否在
树中。

等待
之后,您的小部件可能不再被装载。执行setState时会出现一个异常。这实际上是一件好事,下面的代码
void setStateIfMounted(f) {
  if (mounted) setState(f);
}