Home > database >  A value of type 'String?' can't be assigned to a variable of type 'String'.
A value of type 'String?' can't be assigned to a variable of type 'String'.

Time:04-11

I meet an error on val. It says

A value of type 'String?' can't be assigned to a variable of type 'String'.
import 'package:flutter/material.dart';

class DropDown extends StatefulWidget {
  const DropDown({Key? key}) : super(key: key);

  @override
  State<DropDown> createState() => _DropDownState();
}

class _DropDownState extends State<DropDown> {
  String dropdownValue = "Choose Currency";
  List<String> currnecy = ["SUTRAQ", "USD", "NGN"];
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
      body: Center(
        child: DropdownButton<String>(
            value: dropdownValue,
            items: currnecy.map((String currencyName) {
              return DropdownMenuItem<String>(
                child: Text(currencyName),
                value: currencyName,
              );
            }).toList(),
            onChanged: (val) {
              setState(() {
                dropdownValue = val;
              });
            }),
      ),
    ));
  }
}

CodePudding user response:

The parameter of the onChanged of the DropdownButton is nullable String?, so it means val can be null. You defined your variable dropdownValue as non-nullable (String and not String?) so it doesn't accept the null value.

I guess the value of the onChanged can be null if the user dismisses the dropdown without choosing any option.

You have several options:

Option 1: Make your variable nullable:

  String? dropdownValue = "Choose Currency";

Option 2: Ignore val when it is null:

onChanged: (val) {
  if (val == null) return;
  setState(() {
    dropdownValue = val;
  });
}),

Option 3: Replace val with a non-nullable string:

onChanged: (val) {
  setState(() {
    dropdownValue = val ?? '';
  });
}),

CodePudding user response:

the method onChanged takes String? as a parameter:

onChanged: (String? value) {
    setState(() {
      dropdownValue = value;
    });
  

change: String dropdownValue = "Choose Currency";

to: String? dropdownValue = "Choose Currency";

OR change val in onChanged to nullable, like this:

onChanged: (val) {
          setState(() {
            dropdownValue = val!;
          });
  • Related