flutter - 报错: setState() or markNeedsBuild() called during build

当首次进入页面, 弹出自定义的引导页面

代码如下

@override
  initState() {
    super.initState();
    showTipsView();
 }

showTipsView() {
	showGeneralDialog(context: context,
      barrierDismissible: false,
      barrierLabel: "",
      barrierColor: Colors.black.withAlpha(40),
      transitionDuration: Duration(milliseconds: 200),
      pageBuilder: (BuildContext context, Animation animation,
          Animation secondaryAnimation) {
        return Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(left: 30, right: 30),
          child: Card(
              child: **自定义view**
        ));
      });
}

运行完发现报错: setState() or markNeedsBuild() called during build.
原因就是字面意思, 在build的时候不允许调用setState() 或markNeedsBuild().
那什么时候页面才build完成了呢?

答案是:

/// Schedule a callback for the end of this frame.
  ///
  /// Does *not* request a new frame.
  ///
  /// This callback is run during a frame, just after the persistent
  /// frame callbacks (which is when the main rendering pipeline has
  /// been flushed). If a frame is in progress and post-frame
  /// callbacks haven't been executed yet, then the registered
  /// callback is still executed during the frame. Otherwise, the
  /// registered callback is executed during the next frame.
  ///
  /// The callbacks are executed in the order in which they have been
  /// added.
  ///
  /// Post-frame callbacks cannot be unregistered. They are called exactly once.
  ///
  /// See also:
  ///
  ///  * [scheduleFrameCallback], which registers a callback for the start of
  ///    the next frame.
  void addPostFrameCallback(FrameCallback callback) {
    _postFrameCallbacks.add(callback);
  }

我们的代码就可以修改成这样:

@override
  initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      showTipsView();
    });
 }

你可能感兴趣的:(flutter)