1
votes

I am getting this exception while trying to navigate to another page using Navigator.of(context).push() :

lib/main.dart:20:41: Error: A function expression can't have a name. Navigator.push(context, MaterialPageRoute(builder: context){ ^^^^^^^^^^^^^^^^^ lib/main.dart:20:68: Error: Not a constant expression. Navigator.push(context, MaterialPageRoute(builder: context){ ^^^^^^^ lib/main.dart:20:66: Error: Non-optional parameters can't have a default value. Try removing the default value or making the parameter optional. Navigator.push(context, MaterialPageRoute(builder: context){ ^ lib/main.dart: Error: The argument type 'HomePage Function(dynamic)' can't be assigned to the parameter type 'Route'.

Code :

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Are You Present?',
        debugShowCheckedModeBanner: false,
        home: Scaffold(
          body: Center(
            child:
                FlatButton(onPressed: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(builder: context){
                      return HomePage();
                    }
                  );
                }, child: Text("Press to Continue")),
          ),
        ));
  }
}
2
Please don't post screenshots of your code! It is hard to search or copy! - Martin Fink

2 Answers

2
votes

This is the correct way to use Navigator.of(context).push() :

Try changing the code inside the onPressed with following

Navigator.of(context).push(MaterialPageRoute(
            builder: (context){
              return HomePage();
            }
          ));
0
votes
Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return Demo();
              },
            ),
          );

the builder takes a function as an input and we have provided an anonymous function having parameter as current context and we returned the class that we want to push on the stack if the button is pressed.