Info TechCourse
Info TechCourse

Reputation: 11

Errors in dart class

So I'm working on this quiz app, and I just create a class for my question and answers. But vscode keeps telling me that there are errors. Can someone please help me?

Here is the main.dart

import 'package:flutter/material.dart';
import 'question.dart';

void main() {
  runApp(HomePage());
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.grey[900],
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: Quizzler(),
          ),
        ),
      ),
    );
  }
}

class Quizzler extends StatefulWidget {
  @override
  QuizzlerState createState() => QuizzlerState();
}

class QuizzlerState extends State<Quizzler> {
  List<Widget> scoreKeeper = [];

  List<Domande> domandeBank = [
    Domande(d: 'Il sole è una stella', r: true),
    Domande(d: 'Il latte è verde', r: false),
    Domande(d: 'Il mare è blu', r: true),
  ];

  int qNumber = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
          flex: 5,
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Center(
              child: Text(
                domandeBank[qNumber].domande,
                style: TextStyle(color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextButton(
              style: TextButton.styleFrom(padding: EdgeInsets.zero),
              child: Container(
                color: Colors.green,
                height: 50,
                width: double.infinity,
                child: Center(
                  child: Text(
                    "True",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
              onPressed: () {
                setState(() {
                  bool risCorretta = domandeBank[qNumber].risposte;
                  if (risCorretta == true) {
                    scoreKeeper.add(
                      Icon(
                        Icons.check,
                        color: Colors.green,
                      ),
                    );
                  } else {
                    scoreKeeper.add(
                      Icon(
                        Icons.close,
                        color: Colors.red,
                      ),
                    );
                  }
                  qNumber++;
                });
              },
            ),
          ),
        ),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextButton(
              style: TextButton.styleFrom(padding: EdgeInsets.zero),
              child: Container(
                color: Colors.red,
                height: 50,
                width: double.infinity,
                child: Center(
                  child: Text(
                    "False",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
              onPressed: () {
                setState(() {
                  bool risCorretta = domandeBank[qNumber].risposte;
                  if (risCorretta == false) {
                    scoreKeeper.add(
                      Icon(
                        Icons.check,
                        color: Colors.green,
                      ),
                    );
                  } else {
                    scoreKeeper.add(
                      Icon(
                        Icons.close,
                        color: Colors.red,
                      ),
                    );
                  }
                  qNumber++;
                });
              },
            ),
          ),
        ),
        Row(
          children: scoreKeeper,
        ),
      ],
    );
  }
}

And here is the question.dart class

class Domande {
  String domande;
  bool risposte;

  Domande({String d, bool r}) {
    domande = d;
    risposte = r;
  }
}

And the errors i get:

Non-nullable instance field 'domande' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.


Non-nullable instance field 'risposte' must be initialized.
Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.


The parameter 'd' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.

The parameter 'r' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.

Upvotes: 1

Views: 426

Answers (2)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29783

The errors is related to Null Safety in Flutter. Which basically means, you need to handle the null value on your code.

When you're using the following code:

class Domande {
  String domande;
  bool risposte;

  Domande({String d, bool r}) {
    domande = d;
    risposte = r;
  }
}

in the constructor, Domande({String d, bool r}) you defined a non-required parameters, so then you can use the following code:

var item = Domande();

which defaulting the parameters d and r as null. But Null Safety feature force you to define the nullable parameters. So, then, you need to change your code to:

class Domande {
  String? domande; // nullable
  bool? risposte; // nullable

  Domande({String d, bool r}) {
    domande = d;
    risposte = r;
  }
}

Then, whenever you're using the Domande class, you need to handle the null value of domande and risposte.

Alternatively, you can force your Domande creation to always have a non-null value by adding required keyword to the parameters:

class Domande {
  String domande;
  bool risposte;

  Domande({required String d, required bool r}) {
    domande = d;
    risposte = r;
  }
}

Hence, you don't need to handle the null value. But you forced to create the object with the following code:

var item = Domande(d: "d", r:false);

Upvotes: 0

quoci
quoci

Reputation: 3557

First of all you can omit this part.

domande = d;
risposte = r;

The pattern of assigning a constructor argument to an instance variable is so common, but with dart you can just do it like the code snippet below.
Now we come to your problem. First of all you are using null-safety and created you variable to not be nullable. Then you created your constructors with optional parameters, this means those parameters can be null, but you class variables can't be null. This is the reason why you this error occurs.
You can fix this by using the keyword required which means you variables are mandatory.

class Domande {
  String domande;
  bool risposte;

  Domande({required this.domande, required this.risposte});
}

Another way to fix this is to make your variables nullable by using the ?. But then make sure you handle the case if those variables are null.

class Domande {
  String? domande;
  bool? risposte;

  Domande({this.domande, this.risposte});
}

Upvotes: 1

Related Questions