Home > front end >  how can i fix : Navigator operation requested with a context that does not include a Navigator
how can i fix : Navigator operation requested with a context that does not include a Navigator

Time:01-19

I´m new in flutter and i´m trying to create a navigation to another page called Registro();

I'm trying with this solutionthat i found in a post here in stackoverflow.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(home: Login());
  }
}

class Login extends StatelessWidget {
  const Login({Key? key}) : super(key: key);
  static const String _title = 'Sample App';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
        bottomNavigationBar: BottomAppBar(
          elevation: 3,
          child: Row(
            children: <Widget>[
              const Text('¿No tienes una cuenta?'),
              TextButton(
                child: const Text(
                  'Registrate',
                  style: TextStyle(fontSize: 20),
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => new Registro()),
                  );
                },
              )
            ],
            mainAxisAlignment: MainAxisAlignment.center,
          ),
        ),
      ),
    );
  }
}

Also i tried this solution -> and doesnt works :c

Navigator operation requested with a context that does not include a Navigator

CodePudding user response:

If you want to use Navigator.push(context, yourPageRoute), (which does a Navigator.of(context)), context needs to be able to access a Navigator placed above in the widget tree. Usually, this Navigator is the root one that is being built in MaterialApp.

I your case you have

Widget build(BuildContext context) {
  return MaterialApp(  // <- The Navigator is inside this widget.
    // ...
    TextButton(
      onPressed: () {
        Navigator.of(context);
        // ...
      }, 
    ),
  );
}

But the context you are using comes from the build method of MyApp, which is not below the MaterialApp widget you are using.

So you need to use the context that comes from below the MaterialApp in the widget tree.

How to solve it

You could use a Builder widget to be able to access the context from its builder method:

Widget build(BuildContext context) {
  return MaterialApp(  // <- The Navigator is inside this widget.
    // ...
    Builder(
      builder: (context) {
        return TextButton(
          onPressed: () {
            Navigator.of(context); // <- Now the context comes from Builder which is below MaterialApp and you should be able to access its Navigator.
            // ...
          }, 
        ),
      },
    ),

  );
}
  • Related