FlutterError (setState() 在 dispose() 之后调用:(生命周期状态:已失效,未安装)

omb*_*iro 8 dart flutter

错误在两个区域引发(并且应用程序冻结(当应用程序最小化时,当点击手机后退按钮时,或者当另一个应用程序在颤振应用程序之上运行时。颤振版本: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);
}
Run Code Online (Sandbox Code Playgroud)

第二个区域在以下代码中,我也得到了::

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');
 });
}
Run Code Online (Sandbox Code Playgroud)

}

来自 FRAMEWORK.DART 的 FABbottomAppBarState 错误。

在 HomePage() 上的 getItems 上抛出相同的错误

发生异常。FlutterError (setState() 在 dispose() 之后调用: FABBottomAppBarState#250ac(lifecycle state: defunct, not installed) 如果您在 State 对象上为不再出现在小部件树中的小部件调用 setState(),则会发生此错误(例如,其父小部件在其构建中不再包含该小部件。当代码从计时器或动画回调中调用 setState() 时,可能会发生此错误。首选解决方案是取消计时器或停止在 dispose() 中收听动画回调。另一种解决方案是在调用 setState() 之前检查此对象的“mounted”属性,以确保该对象仍在树中。如果 setState() 正在被调用,则此错误可能表示内存泄漏,因为另一个对象正在保留在从树中删除后对该 State 对象的引用。

进一步的调查表明,该应用程序为手机占用了大约 400MB 的内存(Ram),我觉得这太高了。

帮助找出问题将真正有帮助。提前致谢。

附加信息:在 android 7.0、flutter 1.20.2 上运行时发生错误。请参阅https://github.com/flutter/flutter/issues/35900上的类似/相关问题。请注意,我升级到 Flutter 1.20.2 并降级到 1.7.5 需要我在升级后进行大量更改,尤其是在 Firestore 上(注意:https ://firebase.flutter.dev/docs/migration最近更新)。

Gaz*_*kus 17

之后await,您的小部件可能不再安装。做 setState 会在那个时候给你一个例外。这实际上是一件好事,无论如何都不应该执行后面的代码,因为您在其他地方。

关于在 dispose() 之后调用的“setState()”异常,您有三个选项:

  1. 安全地忽略它。例外是保存您的功能以免继续。
  2. if (!mounted) return;在每个await和之间放置一个setState()。把它放在 each 之后可能是一个好习惯await
  3. 将您的setState()电话替换为setStateIfMounted()并将其定义为:
void setStateIfMounted(f) {
  if (mounted) setState(f);
}
Run Code Online (Sandbox Code Playgroud)

我在这个视频中解释了这些方法。

  • 好吧,这只是隐藏了错误,因为 setState 没有被调用,而它应该被调用,但以延迟的方式。 (2认同)

voi*_*oid 13

您可以使用:

  if (this.mounted) { // check whether the state object is in tree
    setState(() {
      // make changes here
    });
  }
Run Code Online (Sandbox Code Playgroud)

mounted此检查是否无论State对象是目前在tree挂载类


小智 5

@override
void setState(VoidCallback fn) {
  if (!mounted) return;
  super.setState(fn);
}
Run Code Online (Sandbox Code Playgroud)