Flutter报setState() or markNeedsBuild() called during build.错误解决办法

在Flutter中,假如我们在GridView 的itemBuilder中动态加载数据时,很可能会报下面这个错误:

The following assertion was thrown building:
I/flutter (29019): setState() or markNeedsBuild() called during build.
I/flutter (29019): This GridViewWidget widget cannot be marked as needing to build because the framework is already in
I/flutter (29019): the process of building widgets. A widget can be marked as needing to be built during the build
I/flutter (29019): phase only if one of its ancestors is currently building. This exception is allowed because the
I/flutter (29019): framework builds parent widgets before children, which means a dirty descendant will always be
I/flutter (29019): built. Otherwise, the framework might not visit this widget during this build phase.
I/flutter (29019): The widget on which setState() or markNeedsBuild() was called was:
I/flutter (29019): GridViewWidget(state: _GridViewVBuilder#b79b6)
I/flutter (29019): The widget which was currently being built when the offending call was made was:
I/flutter (29019): SliverGrid(delegate: SliverChildBuilderDelegate#bd5f6(estimated child count: 100), renderObject:
I/flutter (29019): RenderSliverGrid#719a8 relayoutBoundary=up2 NEEDS-LAYOUT)

示例:

import 'package:flutter/material.dart';

/*
* 
* 网格布局
* */
class GridViewWidget extends StatefulWidget {
  @override
  State createState() {
    return _GridViewVBuilder();
  }
}

class _GridViewVBuilder extends State {
  List indexs = List.generate(100, (index) {
    return index;
  });

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5),
      itemCount: indexs.length,
      itemBuilder: (context, index) {
        /*当数据加载完毕时 追加数据*/
        if (index == indexs.length - 1) {
          _addIndex();
        }

        return Text(
          "$index",
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Colors.red,
            fontSize: 20,
          ),
        );
      },
    );
  }

  void _addIndex() {
    setState(() {
      indexs.add(indexs.length + 1);
    });
  }
}

Flutter报setState() or markNeedsBuild() called during build.错误解决办法_第1张图片

原因是因为控件还没有构建完毕,延时加载即可解决问题

例如:

  void _addIndex() {
    /*这里要延时加载  否则会抱The widget on which setState() or markNeedsBuild() was called was:错误*/
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      setState(() {
        indexs.add(indexs.length + 1);
      });
    });
  }
}


如果你觉得本文对你有帮助,麻烦动动手指顶一下,算是对本文的一个认可。也可以关注我的 Flutter 博客专栏,我会不定期的更新,如果文中有什么错误的地方,还望指正,转载请注明转自喻志强的博客 ,谢谢!

你可能感兴趣的:(Flutter)