Search code examples
flutterdartandroid-studiotypeerror

How to fix "String?' can't be assigned to 'String'" in Dart/Flutter?


I'm encountering an error:

"The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't."

in my Dart/Flutter code (specifically lib/screens/home_screen.dart:71). Here's the relevant code snippet:

Code:

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

  @override
  State<Home> createState() => _HomeState();
}
const _btnTextStart = 'Start Pomodoro';
const _btnTextResumePomodoro = 'Resume Pomodoro';

class _HomeState extends State<Home> {

  int remainingTime = pomodoroTotalTime;
  String mainBtnText = _btnTextStart;
  PomodoroStatus pomodoroStatus = PomodoroStatus.pausedPomodoro;
  late Timer _timer;
  int pomodoroNum = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(children: [
            SizedBox(height: 10,),
            Text(“Pomodoro number:$pomodoroNum”,
              style: TextStyle(fontSize: 32, color: Colors.white),
            ),
            Expanded(
                  children: [
                      progressColor: statusColor[pomodoroStatus],
                    ),
                  
                    ProgressIcons(
                      total: pomodoroPerSet,
                      done: pomodoroNum - (setNum * pomodoroPerSet),
                    ),
                    Text(
                      statusDescription[PomodoroStatus],// Line 71 likely causing the issue 
                    style: TextStyle(color: Colors.white),
                    ),
                 
                  ],

                ),
            ),
          ],
         ),
        ),
      )
    );
  }

I understand this is related to Dart's null safety. I've tried changing the variable PomodoroStatus to start with a capital "P", but it didn't resolve the issue. Could you please help me understand how to fix this error?


Solution

  • Solution:

    Change:

    statusDescription[PomodoroStatus]
    

    to this:

    statusDescription[pomodoroStatus]!
    

    Explanation:

    The Text widget expects a String and the result of statusDescription[pomodoroStatus] is nullable i.e is of type String?.

    String? is not equivalent to String so you need to cast it to String by adding ! after the nullable variable.

    Note:

    Only use this if you're sure that statusDescription[pomodoroStatus] is not null.

    If you're not sure, you can do a null-check and give a default variable if it is null.

    Like this:

    statusDescription[pomodoroStatus] ?? 'default status'