Search code examples
flutterdartmobxobserver-patternprovider

Exception: Error happened when building Observer, but it was captured since disableErrorBoundaries==true


I am returning below widget in my build method of StatefulWidget class in flutter app:

return Stack(
  children: [
    Observer(
      builder: (context) {
        return SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Column(
            children: [
              _dashboardStore.showFirstPageLoading == false
                  ? _buildDashboardTableDataWidgets()
                  : Container(),
              _dashboardStore.showFirstPageLoading == false
                  ? _buildFactAndFigureWidget()
                  : Container(),
              //_showSearchAndSummaryList(),
            ],
          ),
        );
      },
    ),
    _showRetryButton(),
    _showLoader()
  ],
);

You can notice that I am using Observer and using mobx state management in flutter. Here, _dashboardStore is the class which with mixin Store and initialized as below:

_dashboardStore = Provider.of<DashboardStore>(context, listen: false);

In my above Widget I am using below observable fields which is their inside DashboardStore as:

@observable
  DashboardTableDataRes? dashboardTableDataRes;

  @observable
  FactAndFigureDataRes? dashboardFactAndFigureRes;

But I am getting below exception while running the app:

The following _Exception was thrown building Observer(dirty): Exception: Error happened when building Observer, but it was captured since disableErrorBoundaries==true

The relevant error-causing widget was: Observer Observer:file:///home/growexx/StudioProjects/flutter-mobile-app/lib/ui/dashboard/dashboard_view.dart:92:9

Below is the dependency I am using in pubspec.yaml file:

mobx: ^2.0.1
  flutter_mobx: ^2.0.0
  provider: ^6.0.0

and below are the dev dependencies:

  mobx_codegen: ^2.0.1+3
  build_runner: ^2.0.3

What am I doing wrong here or What might be the issue?


Solution

  • Your direct return of singleChildScrollView without first ensuring null safety may be the problem.

    So, you can try the below method to avoid this error:

    Observer(
      builder: (context) {
        // check for null safety first
        if (_dashboardStore.dashboardTableDataRes == null && 
            _dashboardStore.dashboardFactAndFigureRes == null) {
         return Container(); // Return loading or any Other error widget you want
        }
    
        // Continue to build your UI without null data
        // your widget
        return SingleChildScrollView(
        );
      },
    ),
    

    Also, I'm assuming _dashboardStore.showFirstPageLoading == false in your store (controller) you initialized with the default value.

    If not, then also try null safe for _dashboardStore.showFirstPageLoading == false also and return loading or something you want in your code.