Функция сборки вернула null. Виджет-нарушение: BlocBuilder ‹NotificationBloc, NotificationState› в пакете flutter_bloc

Я новичок в flutter, а также в flutter_bloc, где я пытаюсь получить виджет в blocbuilder, но получаю сообщение «Функция сборки вернула null. Неприятный виджет: BlocBuilder. Функции сборки никогда не должны возвращать null». Ниже приведен код блока, а также нулевая ошибка с консоли.

        Column(
          children: <Widget>[
            Container(
              color: Colors.white,
              child: BlocListener<NotificationBloc, NotificationState>(
                listener: (context, state) {
                },
                child: BlocBuilder<NotificationBloc, NotificationState>(
                  builder: (context, state) {
                    if (state is NotificationLoadedState) {
                      return NotificationIconBuild();
                    }
                  },
                ),
              ),
            )
          ],
        )
  Widget NotificationIconBuild() {
    return Column(
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.notifications),
          onPressed: () {},
        ),
        IconButton(
          icon: Icon(Icons.notifications),
          onPressed: () {},
        ),])}

Ошибка из журнала консоли

I/flutter (13632): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (13632): The following assertion was thrown building BlocBuilder<NotificationBloc, NotificationState>(dirty,
I/flutter (13632): state: _BlocBuilderBaseState<NotificationBloc, NotificationState>#7fa62):
I/flutter (13632): A build function returned null.
I/flutter (13632): The offending widget is:
I/flutter (13632):   BlocBuilder<NotificationBloc, NotificationState>
I/flutter (13632): Build functions must never return null.
I/flutter (13632): To return an empty space that causes the building widget to fill available room, return
I/flutter (13632): "Container()". To return an empty space that takes as little room as possible, return
I/flutter (13632): "Container(width: 0.0, height: 0.0)".
I/flutter (13632): 
I/flutter (13632): The relevant error-causing widget was:
I/flutter (13632):   BlocBuilder<NotificationBloc, NotificationState>
I/flutter (13632):   file:///C:/Users/Nabil/AndroidStudioProjects/flutter_save/lib/home_page.dart:77:24

person mohammed nabil    schedule 19.01.2020    source источник


Ответы (3)


Это происходит потому, что вы указываете только одно if условие для своего состояния, равное NotificationLoadedState. Ваш Блок, должно быть, пытался создать другое состояние, которое не указано, поэтому в результате BlocBuilder возвращается null.

Для быстрого исправления вы можете пока просто изменить свой BlocBuilder на что-то вроде этого.

                child: BlocBuilder<NotificationBloc, NotificationState>(
                  builder: (context, state) {
                    if (state is NotificationLoadedState) {
                      return NotificationIconBuild();
                    } else {
                      return Container();,
                    }
                  },
                ),
person Federick Jonathan    schedule 19.01.2020

Это происходит потому, что BlocBuilder требует возврата. Но вы определили возврат только тогда, когда условие истинно. Но когда условие ложно, оно вернет null. Вот почему он выдает эту ошибку. Поэтому вы должны добавить блок else или инструкцию return.

А в новой версии bloc, если вы хотите использовать BlocBuilder и BlocListener вместе, вы можете использовать виджет BlocConsumer.

Вы можете проверить это: Пример BlocConsumer

person thisisyusub    schedule 27.01.2020

Одна вещь, которая действительно глупая, заключается в том, что я использовал BlocListener вместо BlocBuilder, и это вызывает указанную выше ошибку, надеюсь, это может кому-то помочь.

person Doan Bui    schedule 16.07.2021