Home > Mobile >  Flutter beginner question about context inside Navigator class
Flutter beginner question about context inside Navigator class

Time:01-25

I'm not sure what context means inside a Navigator, I get an error if I don't use it, but when I use it I get this error:

Undefined name 'context'. Try correcting the name to one that is defined, or defining the name.

So how do I define context exactly. Sorry for the trouble, it's probably something very simple.

I'm trying to get a button to change to a new page when clicked here's the onPressed:

FloatingActionButton.extended(
  onPressed: () {
    Navigator.pushNamed(context, '/Page2');
  },

Here's some more of my code if it helps

class MyApp extends StatelessWidget {
  const MyApp({Key key = const ValueKey("MyApp")});

  @override
  Widget build(BuildContext context) {
    return Navigator(
      initialRoute: '/',
      onGenerateRoute: _onGenerateRoute,
    );
  }

  MaterialPageRoute _onGenerateRoute(RouteSettings settings) {
    WidgetBuilder builder = (BuildContext _) => Scaffold(
          body: Center(
            child: Text("Page Not Found"),
          ),
        );
    switch (settings.name) {
      case '/':
        builder = (BuildContext _) => Scaffold(
...
        break;
      case '/quiz':
        builder = (BuildContext _) => QuizPage();
        break;
    }
    return MaterialPageRoute(builder: builder, settings: settings);
  }
}

I tried searching it up and even asking ChatGPT but I couldn't make heads or tails of what they were saying. Sorry if I haven't tried hard enough.

CodePudding user response:

I'm guessing that your FloatingActionButton piece of code is inside the _onGenerateRoute method, right?
If that's the case, the error is thrown because context is an argument of the build method of MyApp and not of _onGenerateRoute, or, as the error mentions, is an undefined variable in _onGenerateRoute.

You have instead named the BuildContext variable as _ here:

MaterialPageRoute _onGenerateRoute(RouteSettings settings) {
    WidgetBuilder builder = (BuildContext _) => Scaffold(

You can probably simply change it this way:

 MaterialPageRoute _onGenerateRoute(RouteSettings settings) {
    WidgetBuilder builder = (BuildContext context) => Scaffold(

to make it work.

EDIT: I now noticed that the same _ is used in every case of your switch: try replacing all of them with context (or paste the code of the case in which the FAB is created)

  • Related