【问题标题】:setState() or markNeedsBuild() called during build, widget was currently being built when offending call was madesetState() 或 markNeedsBuild() 在构建过程中被调用,在进行违规调用时当前正在构建小部件
【发布时间】:2023-02-14 10:00:20
【问题描述】:

我正在尝试使用 flutter 制作一个简单的测验应用程序,但这已经困扰我一天多了

该错误主要指出在构建测验期间调用了 myApp。即使我也在 youtube 上搜索过,我也不知道该怎么做。

错误信息

Main.dart代码:

import 'package:first/result.dart';
import 'package:flutter/material.dart';

import './quiz.dart';
import './result.dart';

void main(List<String> args) => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final _questions = [
    {
      'questionText': 'What\'s your favorite colour?',
      'answers': ['Black', 'Red', 'Blue', 'Green'],
    },
    {
      'questionText': 'What\'s your favorite animal?',
      'answers': ['Cat', 'Dog', 'Pig', 'Parrot'],
    },
    {
      'questionText': 'Who\'s your favorite wrestler?',
      'answers': ['Seth Rollins', 'Roman Reigns', 'John Cena', 'Randy Orton'],
    },
  ];
  var _questionIndex = 0;

  void _answerQuestion() {
    setState(() {});
    _questionIndex = _questionIndex + 1;
    print(_questionIndex);

    if (_questionIndex < _questions.length) {
      print('We have more Questions for you !!');
    } else {
      print('No more questions left !!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My First App'),
        ),
        body: _questionIndex < _questions.length
            ? Quiz(
                answerQuestion: _answerQuestion,
                questionIndex: _questionIndex,
                questions: _questions)
            : Result(),
      ),
    );
  }
}

quiz.dart代码:


import './question.dart';
import './answer.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;

  Quiz({required this.questions, required this.answerQuestion, required this.questionIndex});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Question(questions[questionIndex]['questionText'] as String),
        ...(questions[questionIndex]['answers'] as List<String>).map((answer) {
          return Answer(answerQuestion(), answer);
        }).toList()
      ],
    );
  }
}

结果.飞镖代码:

import 'package:flutter/material.dart';

class Result extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('All questions are answered !!'),
    );
  }
}

answer.dart代码:

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final VoidCallback selectHandler;
  final String answerText;

  Answer(this.selectHandler, this.answerText);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: RaisedButton(
          color: Colors.blue,
          textColor: Colors.white,
          onPressed: selectHandler,
          child: Text(answerText)),
    );
  }
}

问题.飞镖代码:

import 'package:flutter/material.dart';

class Question extends StatelessWidget {
  final String questionText;

  Question(this.questionText);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(10.0),
      child: Text(questionText,
          style: TextStyle(fontSize: 28), textAlign: TextAlign.center),
    );
  }
}

请帮助。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    使用 Function 时,主要问题出现在 Answer 和 Quiz 小部件上。

    在Quiz 上使用VoidCallback 而不是Funtion。

    class Quiz extends StatelessWidget {
      final List<Map<String, Object>> questions;
      final int questionIndex;
      final VoidCallback answerQuestion;
    
      const Quiz({
        Key? key,
        required this.questions,
        required this.answerQuestion,
        required this.questionIndex,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Question(questions[questionIndex]['questionText'] as String),
            ...(questions[questionIndex]['answers'] as List<String>).map(
              (answer) {
                return Answer(answerQuestion, answer);
              },
            ).toList()
          ],
        );
      }
    }
    

    全SN-P

    import 'package:flutter/material.dart';
    
    void main(List<String> args) => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _MyAppState();
      }
    }
    
    class _MyAppState extends State<MyApp> {
      final _questions = [
        {
          'questionText': 'What's your favorite colour?',
          'answers': ['Black', 'Red', 'Blue', 'Green'],
        },
        {
          'questionText': 'What's your favorite animal?',
          'answers': ['Cat', 'Dog', 'Pig', 'Parrot'],
        },
        {
          'questionText': 'Who's your favorite wrestler?',
          'answers': ['Seth Rollins', 'Roman Reigns', 'John Cena', 'Randy Orton'],
        },
      ];
      var _questionIndex = 0;
    
      void _answerQuestion() {
        setState(() {});
        _questionIndex = _questionIndex + 1;
        print(_questionIndex);
    
        if (_questionIndex < _questions.length) {
          print('We have more Questions for you !!');
        } else {
          print('No more questions left !!');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('My First App'),
            ),
            body: _questionIndex < _questions.length
                ? Quiz(
                    answerQuestion: _answerQuestion,
                    questionIndex: _questionIndex,
                    questions: _questions)
                : Result(),
          ),
        );
      }
    }
    
    class Quiz extends StatelessWidget {
      final List<Map<String, Object>> questions;
      final int questionIndex;
      final VoidCallback answerQuestion;
    
      const Quiz({
        Key? key,
        required this.questions,
        required this.answerQuestion,
        required this.questionIndex,
      }) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Question(questions[questionIndex]['questionText'] as String),
            ...(questions[questionIndex]['answers'] as List<String>).map(
              (answer) {
                return Answer(answerQuestion, answer);
              },
            ).toList()
          ],
        );
      }
    }
    
    class Answer extends StatelessWidget {
      final VoidCallback selectHandler;
      final String answerText;
    
      Answer(this.selectHandler, this.answerText);
    
      @override
      Widget build(BuildContext context) {
        return SizedBox(
          width: double.infinity,
          child: RaisedButton(
            color: Colors.blue,
            textColor: Colors.white,
            onPressed: selectHandler,
            child: Text(answerText),
          ),
        );
      }
    }
    
    class Question extends StatelessWidget {
      final String questionText;
    
      Question(this.questionText);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          width: double.infinity,
          margin: EdgeInsets.all(10.0),
          child: Text(questionText,
              style: TextStyle(fontSize: 28), textAlign: TextAlign.center),
        );
      }
    }
    
    class Result extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Text('All questions are answered !!'),
        );
      }
    }
    

    【讨论】:

    • VoidCallback 本质上是 void Function(),所以这不应该导致错误,先生。我假设,错误是由传递函数实例而不是函数引起的,即传递 _answerQuestion 而不是 lambda 函数 () =&gt; _answerQuestion()
    • 在回调时它使用 setState 并分配为 Answer(answerQuestion(),,这是主要原因,我想我刚刚更改了它,我正在分享您可以测试的完整 sn-p
    【解决方案2】:

    您收到错误消息的原因是每次调用 MyApp 小部件的构建方法时您都在调用 setState。 setState 方法会重新触发 widget 的构建,然后再次调用 setState。所以基本上你有一个无限的重新渲染。

    如果您查看 quiz.dart 中的代码,我们会找到这种无限重新渲染的原因:

    @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Question(questions[questionIndex]['questionText'] as String),
            ...(questions[questionIndex]['answers'] as List<String>).map((answer) {
              return Answer(answerQuestion() /*<-- here is the problem*/, answer);
            }).toList()
          ],
        );
      }
    

    每次测验小部件调用它的构建方法时,它都会调用 answerQuestion 方法,该方法将调用主小部件的构建方法,而主小部件又会重建测验小部件。您不应在此处调用该方法,而应将此回调方法进一步向下发送到三个答案小部件:

    class Quiz extends StatelessWidget {
      final List<Map<String, Object>> questions;
      final int questionIndex;
      final Function answerQuestion;
    
      Quiz({required this.questions, required this.answerQuestion, required this.questionIndex});
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            Question(questions[questionIndex]['questionText'] as String),
            ...(questions[questionIndex]['answers'] as List<String>).map((answer) {
              return Answer(answerQuestion /* Notice the difference */, answer);
            }).toList()
          ],
        );
      }
    }
    
    class Answer extends StatelessWidget {
      final Function answerQuestion; // I renamed this to answerQuestion, feel free to stick with selectHandler
      final String answerText;
    
      Answer(this.answerQuestion, this.answerText);
    
      @override
      Widget build(BuildContext context) {
        return SizedBox(
          width: double.infinity,
          child: RaisedButton(
              color: Colors.blue,
              textColor: Colors.white,
              onPressed: answerQuestion,
              child: Text(answerText)),
        );
      }
    }
    

    我还建议您更新 answerQuestion 方法小部件中的逻辑,以便将 setState 方法包装在您正在执行的状态更新周围:

    void _answerQuestion() {
        setState(() {
           _questionIndex = _questionIndex + 1;
        });
        print(_questionIndex);
    
        if (_questionIndex < _questions.length) {
          print('We have more Questions for you !!');
        } else {
          print('No more questions left !!');
        }
      }
    

    【讨论】:

      【解决方案3】:

      根据您提供的代码,您似乎只是在 main.dart 代码中将 _answerQuestion 中的函数实例传递到其他文件中。根据我使用 dart 和 flutter 的经验,强烈建议当一个人将一个函数传递给一个小部件时,应该始终以下列方式传递它:

      Quiz(
                      answerQuestion: () => _answerQuestion(), // pass it like this to avoid errors.
                      questionIndex: _questionIndex,
                      questions: _questions)
      
      

      也就是说,您应该将其作为 lambda/匿名函数传递。 IE。

      void yourFunction() {
        // You do something here
      }
      
      AnyWidget(
        onPressed: () => yourFunction();, // This is called a lambda/anonymous function.
      );
      

      这样做的原因是,即使用户实际上没有与应用程序交互,像onPressed: yourFunction, 这样传递的函数也会被调用,即它在构建小部件时被调用。为了避免这种情况,我们使用 lambda 函数。

      如果我的回答有帮助,请将我的回答标记为正确。谢谢你!

      【讨论】:

        【解决方案4】:

        测验中显示错误 ..(questions[questionIndex]['answers'] as ..

        【讨论】:

          猜你喜欢
          • 2021-02-03
          • 2018-05-15
          • 2020-12-12
          • 2020-12-28
          • 2021-01-06
          • 2021-06-06
          • 2021-05-31
          • 2021-08-24
          相关资源
          最近更新 更多