Search code examples
flutterdartdart-null-safety

Operator '+' cannot be called on 'String?' because it is potentially null. In Flutter


I am trying to make an app which takes names then validates it. I got which says : The operator '+' can't be unconditionally invoked because the receiver can be 'null'. I tried to write ' if (value != null), but then i got another error.

Expanded(
    child: ListView.builder(
        itemCount: animeler.length,
        itemBuilder: (BuildContext context, int index) {

            return ListTile(title:
                Text(animeler[index].animeName +
                " : " +
                animeler[index].animePoint.toString()),
                
        })),

This is the class :

class Animes {
  String? animeName = "";
  double animePoint = 0;
  String animeLover = "";


  Animes(String animeName, double animePoint, String animeLover) {
    this.animeName = animeName;
    this.animePoint = animePoint;
    this.animeLover = animeLover;
  }

  
}

This is where i got the anime name. I have a variable anime.

  Widget buildFirstNameField()
  {
    return TextFormField(
      decoration: InputDecoration(labelText: "Anime name", hintText: "Death Note"),
      validator: vallval,
      onSaved: (String? value)
      {
        anime.animeName = value;

      },
    );
  }
}

i call the 'buildFirstNameField' function in:

body: Container(
  margin: EdgeInsets.all(20.0),
  child: Form(
    child: Column(
      children: <Widget>[
        buildFirstNameField(),

Solution

  • animeName is a nullable String, so it is possible to get null, you can provide default value on null case like myNullableVariable ?? defaultValue

    But you can use String format here,

     Text("${animeler[index].animeName??""} : ${animeler[index].animePoint.toString()}")