skip to Main Content

We are running flutter null safety migration and completed the same but while running the app we are facing Unhandled Exception: type ‘Null’ is not a subtype of type ‘String’

static Future<AppStrings> getAppText(String local) async {
var appTextBox = await Hive.openBox("appTextBox");
 AppStrings appText = new AppStrings(
  mainPageTitle: appTextBox.get('mainPageTitle'), ==> error on this line 
  ....
);
return appText;}

I’ve tried adding static Future<AppStrings?> && AppStrings? appText as suggested in other solutions but it throws further error
Error: The argument type 'AppStrings?' can't be assigned to the parameter type 'AppStrings' because 'AppStrings?' is nullable and 'AppStrings' isn't.

2

Answers


  1. I don’t know what AppStrings is but it seems that mainPageTitle in there is a String and appTextBox.get('mainPageTitle') is returning null and you can’t do that.

    There’s two possible options:

    1. Make mainPageTitle in AppStrings nullable, by change the String there to String?. This probably requires you to make additional changes in your code to handle it being nullable, so it easier to do the second option.
    2. Or, you make it fall back to empty string in the case it’s null. This can be done by writing mainPageTitle: appTextBox.get('mainPageTitle') ?? ''
    Login or Signup to reply.
  2. Try this:

    static Future<AppStrings> getAppText(String local) async {
    var appTextBox = await Hive.openBox("appTextBox");
     AppStrings appText = new AppStrings(
      mainPageTitle: appTextBox.get('mainPageTitle') ?? "",
      ....
    );
    return appText;}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search