简体   繁体   English

使用来自另一个 class 的实例访问有状态小部件的变量时,在 null 上调用的 getter 长度

[英]getter length called on null when accessing a variable of a stateful widget using its instance from another class

Initially, I used the page route to send the data to the next page(Question).最初,我使用页面路由将数据发送到下一页(问题)。 (The data is a List Type) (数据为List类型)

Navigator.pushReplacement(context,MaterialPageRoute(
                                        builder: (context) => Question(
                                            questions: this.questions)));

Then I received the value in the Question Stateful class using the constructor and set its value to another variable.然后我使用构造函数接收到 Question Stateful class 中的值并将其值设置为另一个变量。

Question Class:问题 Class:

class Question extends StatefulWidget {
  final List<QuestionModel> questions;

    const Question({this.questions});

  @override
  _QuestionState createState() => _QuestionState();
}

class _QuestionState extends State<Question> {
  @override
  void initState() {
    super.initState();
    print(widget.questions); //<----------working
  }

  @override
  Widget build(BuildContext context){
  return Scaffold(
    body: Column(
      children: <Widget>[
        Timer(),
        SizedBox(height: 40),
        Expanded(child: QuestionBuilder())
      ],
    ),
  );}

when I tried to print the questions List in the Question state, it is perfectly working.当我尝试打印问题 state 中的问题列表时,它工作得很好。

But I need that value in another class QuestionBuilder.但我需要另一个 class QuestionBuilder 中的值。 So, I accessed the value using an instance of the Question Class.因此,我使用问题 Class 的实例访问了该值。

 class QuestionBuilder extends StatefulWidget {
      @override
      _QuestionBuilderState createState() => _QuestionBuilderState();
    }

        class _QuestionBuilderState extends State<QuestionBuilder> {
          List<QuestionModel> questions;

          @override
          void initState() {
            super.initState();
            questions = Question().questions;
            print(questions); //<---------------not working
          } 

         @override
       Widget build(BuildContext context) {
    return PageView.builder(
      itemCount: questions.length ?? 0,
      itemBuilder: (context, index) {
        return SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "Question  ${index + 1} / ",
                      style: Styles.questionNumberTextStyle,
                    ),
                    Text(
                      "7",
                      style:
                          Styles.questionNumberTextStyle.copyWith(fontSize: 20),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Text(
                  questions[index].question,
                  style: Styles.questionTextStyle,
                  textAlign: TextAlign.left,
                ),
              ),
              SizedBox(height: 20),
              option(option: questions[index].option_1, onTap: () {}),
              option(option: questions[index].option_2, onTap: () {}),
              option(option: questions[index].option_3, onTap: () {}),
              option(option: questions[index].option_4, onTap: () {}),
              SizedBox(height: 20),
            ],
          ),
        );
      },
    );
  }}

Now When I print the questions List it is null and further when I used it in a PageView or ListView, the error shows up that the getter length was called on null.现在,当我打印问题列表时,它是 null,当我在 PageView 或 ListView 中使用它时,错误显示在 null 上调用了 getter 长度。

在此处输入图像描述

I don't know what causes the problem.我不知道是什么导致了问题。 Moreover, when tried to manually assign a dummy list value to the question list in Question class.此外,当尝试手动为问题 class 中的问题列表分配一个虚拟列表值时。 It works in the QuestionBuilder class它适用于 QuestionBuilder class

The problem is you are creating a new instance of Question class by using this code:问题是您正在使用以下代码创建问题 class 的新实例:

questions = Question().questions;

One of the simple way is to pass the value in params.一种简单的方法是在参数中传递值。 For example in question class pass the data in parameter where you are calling QuestionBuilder() like this:例如,在问题 class 中,您在调用 QuestionBuilder() 的参数中传递数据,如下所示:

 @override
  Widget build(BuildContext context){
  return Scaffold(
    body: Column(
      children: <Widget>[
        Timer(),
        SizedBox(height: 40),
        Expanded(child: QuestionBuilder(widget.questions),
)
      ],
    ),
  );}

Now define a variable to access this value passed in the param as follows:现在定义一个变量来访问参数中传递的这个值,如下所示:

 class QuestionBuilder extends StatefulWidget {
final List<QuestionModel> questions;
QuestionBuilder(this.questions);
      @override
      _QuestionBuilderState createState() => _QuestionBuilderState();
    }

Now in initState of QuestionBuilder access the questionList as follows:现在在 QuestionBuilder 的 initState 中访问 questionList,如下所示:

 @override
          void initState() {
            super.initState();
            questions = widget.questions;
            print(questions); //<---------------this will work now
          } 

So now your corrected code would be, For Question class:所以现在你更正的代码是,对于问题 class:

class Question extends StatefulWidget {
  final List<QuestionModel> questions;

    const Question({this.questions});

  @override
  _QuestionState createState() => _QuestionState();
}

class _QuestionState extends State<Question> {
  @override
  void initState() {
    super.initState();
    print(widget.questions); 
  }

  @override
  Widget build(BuildContext context){
  return Scaffold(
    body: Column(
      children: <Widget>[
        Timer(),
        SizedBox(height: 40),
        Expanded(child: QuestionBuilder(widget.questions))
      ],
    ),
  );}

and QuestionBuilder would be: QuestionBuilder 将是:

class QuestionBuilder extends StatefulWidget {
final List<QuestionModel> questions;
QuestionBuilder(this.questions);
      @override
      _QuestionBuilderState createState() => _QuestionBuilderState();
    }

        class _QuestionBuilderState extends State<QuestionBuilder> {
          List<QuestionModel> questions;

          @override
          void initState() {
            super.initState();
            questions = widget.questions;
            print(questions); //<---------------not working
          } 

         @override
       Widget build(BuildContext context) {
    return PageView.builder(
      itemCount: questions.length ?? 0,
      itemBuilder: (context, index) {
        return SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "Question  ${index + 1} / ",
                      style: Styles.questionNumberTextStyle,
                    ),
                    Text(
                      "7",
                      style:
                          Styles.questionNumberTextStyle.copyWith(fontSize: 20),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Text(
                  questions[index].question,
                  style: Styles.questionTextStyle,
                  textAlign: TextAlign.left,
                ),
              ),
              SizedBox(height: 20),
              option(option: questions[index].option_1, onTap: () {}),
              option(option: questions[index].option_2, onTap: () {}),
              option(option: questions[index].option_3, onTap: () {}),
              option(option: questions[index].option_4, onTap: () {}),
              SizedBox(height: 20),
            ],
          ),
        );
      },
    );
  }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当从无状态小部件调用到有状态小部件时,变量返回 null? - Variable returns null when called from a Stateless to Stateful Widget? 使用状态小部件访问状态类的方法? - Accessing a method of state class using its stateful widget? 我的_showErrorMessage小部件在null上调用了getter&#39;length&#39; - The getter 'length' was called on null for my _showErrorMessage Widget 访问继承的小部件时,在null上调用了Getter - Getter was called on null while accessing inherited widget 从另一个小部件/ class 更新有状态 class 内的变量 - Update a variable inside stateful class from another widget / class 导航到另一个页面时,在 null 上调用了 getter 'length' - The getter 'length' was called on null when navigate to another page 如何在来自另一个 class 的有状态小部件中触发 function(当 onUnityAdsFinish 时)? - How to trigger a function in a stateful widget from another class (when onUnityAdsFinish)? 使用小部件 object 再次访问时,有状态小部件 class 变量的值发生了变化 - Stateful widget class variable's value changed while accessing again using widget object 当在不同的 class 中调用时,Flutter 变量(getter)始终为 null - Flutter variable (getter) is always null when called in a different class 构建TabBar时,getter&#39;length&#39;在null时调用 - The getter 'length' was called on null when building a TabBar
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM