skip to Main Content

I am building a project in flutter and encountered this error that is mentioning the Null check operator, but I am not using a null check operator.

I have tried all the suggestions I could find in other posts. flutter clear etc.

The only solutions I can find reference the null check operator which is not present in my code.

Could someone please help?

This is the console output when running flutter run. The $appRoute printing is working perfectly so it definitely isn’t null.

available at: http://127.0.0.1:65311/771_ENJaKJI=/
I/flutter ( 9180): AppRoutes: {/: Closure: (dynamic) => HomeScreen, /login: Closure: (dynamic) => LoginScreen, /topics: Closure: (dynamic) => TopicsScreen, /profile: Closure: (dynamic) => ProfileScreen, /about: Closure: (dynamic) => AboutScreen}

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building Builder:
Null check operator used on a null value

The relevant error-causing widget was:
  MaterialApp
  MaterialApp:file:///Users/lbeckert/dev/chatapp/lib/main.dart:58
  :18

When the exception was thrown, this was the stack:
#0      _WidgetsAppState._onGenerateRoute.<anonymous closure>
(package:flutter/src/widgets/app.dart:1422:48)
#1      MaterialPageRoute.buildContent
(package:flutter/src/material/page.dart:53:55)
#2      MaterialRouteTransitionMixin.buildPage
(package:flutter/src/material/page.dart:111:27)
...

═════════════════════════════════════════════════════════════════
═══════════════════════════════════
The Flutter DevTools debugger and profiler on sdk gphone arm64 is
available at:
http://127.0.0.1:9101?uri=http://127.0.0.1:65311/771_ENJaKJI=/

Here is my main.dart file:


import 'package:chatapp/routes.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:chatapp/about/about.dart';
import 'package:chatapp/profile/profile.dart';
import 'package:chatapp/login/login.dart';
import 'package:chatapp/topics/topics.dart';
import 'package:chatapp/home/home.dart';

// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';
import 'services/firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const App());
}

/// We are using a StatefulWidget such that we only create the [Future] once,
/// no matter how many times our widget rebuild.
/// If we used a [StatelessWidget], in the event where [App] is rebuilt, that
/// would re-initialize FlutterFire and make our application re-enter loading state,
/// which is undesired.
class App extends StatefulWidget {
  const App({super.key});

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  Future<FirebaseApp> _initialization = Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return const MaterialApp(
            home: Scaffold(
              body: Center(
                child: Text('error'),
              ),
            ),
          );
        }

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) {
          print('AppRoutes: $appRoutes');
          return MaterialApp(
            routes: appRoutes,
          );
        }

        // Otherwise, show something whilst waiting for initialization to complete
        return const MaterialApp(
          home: Scaffold(
            body: Center(
              child: Text('loading'),
            ),
          ),
        );
      },
    );
  }
}

My routes.dart file:

import 'package:chatapp/profile/profile.dart';
import 'package:chatapp/login/login.dart';
import 'package:chatapp/topics/topics.dart';
import 'package:chatapp/home/home.dart';

var appRoutes = {
  '/': (context) => const HomeScreen(),
  '/login': (context) => const LoginScreen(),
  '/topics': (context) => const TopicsScreen(),
  '/profile': (context) => const ProfileScreen(),
  '/about': (context) => const AboutScreen(),
};

My home.dart file:

import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text('about'),
          onPressed: () => Navigator.pushNamed(context, '/about'),
        ),
      ),
    );
  }
}

and my about.dart file:

import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter/material.dart';

class AboutScreen extends StatelessWidget {
  const AboutScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

3

Answers


  1. Chosen as BEST ANSWER

    After trying around for a couple of hours I found an alternative way of achieving the same thing. The problem seems to be the definition of the initial route "/".

    If you instead use this code:

    // Once complete, show your application
    if (snapshot.connectionState == ConnectionState.done) {
        return MaterialApp(
            routes: appRoutes,
            home: HomeScreen(),
        );
    }
    

    and remove the "/" route from your routes by commenting it out (or deleting the line) like this

    var appRoutes = {
      //'/': (context) => const HomeScreen(),
      '/login': (context) => const LoginScreen(),
      '/topics': (context) => const TopicsScreen(),
      '/profile': (context) => const ProfileScreen(),
      '/about': (context) => const AboutScreen(),
    };
    

    the error goes away.


  2. You should specify an initial route for flutter to navigate to. In your MaterialApp after the print statement:

              return MaterialApp(
                initialRoute: "/",
                routes: appRoutes,
              );
    
    Login or Signup to reply.
  3. Your code does not use the null-check operator (!), but that’s not what your stack trace is pointing to:

    When the exception was thrown, this was the stack:
    #0      _WidgetsAppState._onGenerateRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:1422:48)
    

    You need to inspect flutter/src/widgets/app.dart:1422 from your Flutter SDK. You don’t mention which version of Flutter you’re using, but I’m guessing that that line is from this section of code:

      assert(
        widget.pageRouteBuilder != null,
        'The default onGenerateRoute handler for WidgetsApp must have a '
        'pageRouteBuilder set if the home or routes properties are set.',
      );
      final Route<dynamic> route = widget.pageRouteBuilder!<dynamic>(Probably
        settings,
        pageContentBuilder,
      );
    

    in which case the assert above (which you probably didn’t see because you ran your code only in release mode and not in debug mode) explains what’s wrong.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search