Getting type 'Null' is not a subtype of type 'String' error when using BlocBuilder

Scenario

I am trying to use flutter_bloc for state management in my Flutter app. In my app, I have a button that will appear only if the entered email is valid. For this, I have a _isEmailValid variable initially set to false which updates to true once the entered email is valid.

The button that I want to display is is wrapped in a BlocBuilder as follows:

BlocBuilder<ShowButtonBloc, ShowButtonState>(
                    builder: buildSubmitButton,
                  ),

where buildSubmitButton is as follows:

Widget buildSubmitButton(BuildContext context, ShowButtonState state) {
    if (!_isEmailValid) {
      return const SizeBox();
    } else {
      return GradientButton(
        onTap: () {
          // Navigation logic
        },
        text: labels[31]["labelsText"],
      );
    }
  }

Now, GradientButton is a custom widget which takes in a String parameter called text. When I pass a string such as text: "Proceed", the app runs fine, however, when I try to assign a string from a different map variable, I get the error:

The following _TypeError was thrown building BlocBuilder<ShowButtonBloc, ShowButtonState>(dirty, dependencies: [_InheritedProviderScope<ShowButtonBloc?>], state: _BlocBuilderBaseState<ShowButtonBloc, ShowButtonState>#e4f0a):
type ‘Null’ is not a subtype of type ‘String’

Here, labels is a final List<Map<String, dynamic>> and labels[31]["labelsText"] = "Proceed". The business requires me to store the text in a map for now, and later fetch these contants from an API, which is why can’t merely assign static text to the button.

Here is how my Bloc looks like:

show_button_state.dart

class ShowButtonState {
  final bool show;
  const ShowButtonState({
    required this.show,
  });
}

show_button_event.dart

class ShowButtonEvent {
  final bool show;
  const ShowButtonEvent({
    required this.show,
  });
}

show_button_bloc.dart

class ShowButtonBloc extends Bloc<ShowButtonEvent, ShowButtonState> {
  ShowButtonBloc()
      : super(
          const ShowButtonState(show: false),
        ) {
    on<ShowButtonEvent>(
      (event, emit) => emit(
        ShowButtonState(show: event.show),
      ),
    );
  }
}

Request

I would like to know why I’m getting the error when I pass the string from the variable, and how to fix this issue.

>Solution :

This doesn’t seem to have anything to do with your BLoC.

labels[31]["labelsText"]

did not exist.

Since you did not post that part, it’s hard to help you any further. Make sure this references something that exists. Are there 32 labels (remember, the first one is at index 0)? Does the 32nd have a property "labelsText" that is set to a text? Check for typos, too.

Leave a Reply