1

我是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
4

3 回答 3

3

发生这种情况是因为您只为您的状态指定了一个if条件,即NotificationLoadedState. 您的 Bloc 必须尝试建立其他未指定的状态,因此导致BlocBuilder返回 null。

为了快速修复,您现在可以将您的更改BlocBuilder为类似的内容。

                child: BlocBuilder<NotificationBloc, NotificationState>(
                  builder: (context, state) {
                    if (state is NotificationLoadedState) {
                      return NotificationIconBuild();
                    } else {
                      return Container();,
                    }
                  },
                ),
于 2020-01-19T17:18:42.560 回答
1

发生这种情况是因为 BlocBuilder 需要返回。但是当条件为真时,您只定义了一个返回值。但是当条件为假时,它会返回null。这就是它给出这个错误的原因。所以你必须添加else块或return语句。

而在新版本的 bloc 中,如果你想同时使用 BlocBuilder 和 BlocListener,你可以使用BlocConsumer小部件。

你可以检查一下: BlocConsumer Example

于 2020-01-27T10:44:57.067 回答
0

真正愚蠢的一件事是我使用BlocListener了代替BlocBuilder,它抛出了上述错误,希望它可以帮助某人。

于 2021-07-16T03:37:47.560 回答