Home > Net >  FLUTTER Error: Method 'copyWith' cannot be called on 'TextStyle?' because it is
FLUTTER Error: Method 'copyWith' cannot be called on 'TextStyle?' because it is

Time:02-13

Wow I have a whole lot of these:

Error: Method 'copyWith' cannot be called on 'TextStyle?' because it is potentially null.

  • 'TextStyle' is from 'package:flutter/src/painting/text_style.dart' ('../flutter/packages/flutter/lib/src/painting/text_style.dart'). Try calling using ?. instead.

I don't understand the instruction, I've tried naively appending ? marks in various places, tried changing 'copyWith' to 'apply'.

This is the errourous code:

                    style: Theme.of(context)
                        .textTheme
                        .bodyText2
                        .copyWith(fontWeight: FontWeight.bold)

Uh, I don't get it. Major project changes for this null thing, and a fair amount of the time I feel I'm guessing. My dart files are now littered with !, which seems surprisingly verbose.

Anyway, my project won't compile without this, and I have a good few so help is appreciated.

CodePudding user response:

You have to mark your bodyText2 value as not null with !, but be sure that the bodyText2 value returned is not null, otherwise you will get another error. To read more about null safety: null safety

Theme.of(context).textTheme.bodyText2!.copyWith(fontWeight: FontWeight.bold);
  • Related