【问题标题】:setState() or markNeedsBuild() called during build,showing widget error构建期间调用 setState() 或 markNeedsBuild(),显示小部件错误
【发布时间】:2022-08-22 16:32:58
【问题描述】:

尝试构建测验应用程序,但我在构建错误期间调用了 setState() 或 markNeedsBuild()。出现此错误。这个小部件不能被标记为需要构建,因为框架已经在构建小部件的过程中。

 import \'package:flutter/material.dart\';
    import \'package:my_thera/screens/client/assess/quiz.dart\';
    import \'package:my_thera/screens/client/assess/result.dart\';
    
    class MyAp extends StatefulWidget {
      const MyAp({Key? key}) : super(key: key);
    
      @override
      State<StatefulWidget> createState() {
        return _MyApState();
      }
    }
    
    class _MyApState extends State<MyAp> {
      final _questions = const [
        {
          \'questionText\': \'Q1. Who created Flutter?\',
          \'answers\': [
            {\'text\': \'Facebook\', \'score\': -2},
            {\'text\': \'Adobe\', \'score\': -2},
            {\'text\': \'Google\', \'score\': 10},
            {\'text\': \'Microsoft\', \'score\': -2},
          ],
        },
        {
          \'questionText\': \'Q2. What is Flutter?\',
          \'answers\': [
            {\'text\': \'Android Development Kit\', \'score\': -2},
            {\'text\': \'IOS Development Kit\', \'score\': -2},
            {\'text\': \'Web Development Kit\', \'score\': -2},
            {
              \'text\':
                  \'SDK to build beautiful IOS, Android, Web & Desktop Native Apps\',
              \'score\': 10
            },
          ],
        },
        {
          \'questionText\': \' Q3. Which programing language is used by Flutter\',
          \'answers\': [
            {\'text\': \'Ruby\', \'score\': -2},
            {\'text\': \'Dart\', \'score\': 10},
            {\'text\': \'C++\', \'score\': -2},
            {\'text\': \'Kotlin\', \'score\': -2},
          ],
        },
        {
          \'questionText\': \'Q4. Who created Dart programing language?\',
          \'answers\': [
            {\'text\': \'Lars Bak and Kasper Lund\', \'score\': 10},
            {\'text\': \'Brendan Eich\', \'score\': -2},
            {\'text\': \'Bjarne Stroustrup\', \'score\': -2},
            {\'text\': \'Jeremy Ashkenas\', \'score\': -2},
          ],
        },
        {
          \'questionText\':
              \'Q5. Is Flutter for Web and Desktop available in stable version?\',
          \'answers\': [
            {
              \'text\': \'Yes\',
              \'score\': -2,
            },
            {\'text\': \'No\', \'score\': 10},
          ],
        },
      ];
    
      var _questionIndex = 0;
      var _totalScore = 0;
    
      void _resetQuiz() {
        setState(() {
          _questionIndex = 0;
          _totalScore = 0;
        });
      }
    
      void _answerQuestion(int score) {
        _totalScore += score;
    
        setState(() {
          _questionIndex = _questionIndex + 1;
        });
        // ignore: avoid_print
        print(_questionIndex);
        if (_questionIndex < _questions.length) {
          // ignore: avoid_print
          print(\'We have more questions!\');
        } else {
          // ignore: avoid_print
          print(\'No more questions!\');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text(\'Quiz\'),
            backgroundColor: const Color(0xFF00E676),
          ),
          body: Padding(
            padding: const EdgeInsets.all(30.0),
            child: _questionIndex < _questions.length
                ? Quiz(
                    answerQuestion: _answerQuestion,
                    questionIndex: _questionIndex,
                    questions: _questions,
                  ) //Quiz
                : Result(_totalScore, _resetQuiz),
          ), //Padding
        ); //Scaffold
        //MaterialApp
      }
    }

尝试构建测验应用程序,但我在构建错误期间调用了 setState() 或 markNeedsBuild()。这个小部件不能被标记为需要构建,因为框架已经在构建小部件的过程中。

    标签: flutter


    【解决方案1】:

    如果在build 方法完成之前显示snackBar 或alertDialog,以及在许多其他情况下,您可能会遇到此错误。因此,在这种情况下,您应该使用如下所示的回调函数:

    WidgetsBinding.instance.addPostFrameCallback((_){
    
      // Add Your Code here.
    
    });
    

    或者您也可以使用 SchedulerBinding 执行相同的操作:

    SchedulerBinding.instance.addPostFrameCallback((_) {
    
      // add your code here.
    
      Navigator.push(
            context,
            new MaterialPageRoute(
                builder: (context) => NextPage()));
    });
    

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 2021-02-03
      • 2021-11-14
      • 2021-04-21
      • 2021-12-12
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多