Home > Blockchain >  Flutter: MaterialApp throws Null check operator used error
Flutter: MaterialApp throws Null check operator used error

Time:02-03

Here is where I instantiate my MaterialApp:

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

  static const String _title = 'My New App';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
        title: _title,
        initialRoute: '/special',
        routes: {
          '/special': (context) => const SpecialPage(),
          '/another': (context) => const AnotherPage()
        });
  }
}

The pages are very similar. Here is the Special page:

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Special Stuff'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/another');
          },
          child: const Text('Special Content Goes Here'),
        ),
      ),
    );
  }

When I try to compile I get the error: Null check operator used on a null value. Why?

The error message indicates the problem occurs in the construction of MaterialApp.

CodePudding user response:

Remove the const in the build method of MyApp

Like so:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: _title,
        initialRoute: '/special',
        routes: {
          '/special': (context) => const SpecialPage(),
          '/another': (context) => const AnotherPage()
        });
  }
  •  Tags:  
  • Related