Nullable Error because String is not nullable

Viewed 557

When I run my code, I get the following error message:

The parameter 'name' 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.

Here's my code:

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'checkbox.dart';

class TodoItem extends StatefulWidget {
  final String name;
  final bool? isActive;

  const TodoItem({Key? key, this.name, this.isActive}) : super(key: key);

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

class _TodoItemState extends State<TodoItem> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Text(
          widget.name,
          style: TextStyle(fontSize: 17, color: Colors.grey),
        ),
        Check(
          isActive: widget.isActive,
        )
      ],
    );
  }
}

I tried to solve it with the responses to my last question but that didn't seem to work because apparently Strings are non-nunnable in Dart, even with a "?" besides them.

2 Answers
final String name;

You can not have name = null in this case because you specified the variable to be strictly a string.

final String? name;

By adding a ?, you are making sure that name can contain a string or a null.

So this is one solution


Coming to the constructor part:

TodoItem({Key? key, this.name, this.isActive}) : super(key: key);

Here, this.name is within {} and that makes it an optional parameter until required keyword is specified.

As an optional parameter, the default value of this.name is null which violates the definition of the variable.

Try

TodoItem({Key? key, required this.name, this.isActive}) : super(key: key); // the 'required' modifier.

Which forces the assignment of name variable

or

TodoItem({Key? key, this.name = "", this.isActive}) : super(key: key); // Try adding either an explicit non-'null'

This way, you ensure that even if the optional parameter is not assigned, the default value is not null hence,

final String name;

as a variable declaration is still valid.

Just add the required modifier to this.name in the constructor. You can also set default value to isActive instead of making it nullable.

class TodoItem extends StatefulWidget {
  final String name;
  final bool isActive;

  const TodoItem({
    Key? key,
    required this.name,
    this.isActive = false,
  }) : super(key: key);

  @override
  _TodoItemState createState() => _TodoItemState();
}
Related