Home > Blockchain >  Why Navigator.of(context).pop() back to previous page instead close EndDrawer?
Why Navigator.of(context).pop() back to previous page instead close EndDrawer?

Time:12-01

I have 2 page, page1 and page2. page1 navigate to page2. page2 has endDrawer inside scaffold, but i must wrap scaffold with materialApp. When endDrawer open and i call Navigator.of(context).pop() or Navigator.pop(context), it will back to page1 instead close endDrawer. How to close the endDrawer and not back to page1? all i know to close drawer is use pop

CodePudding user response:

I think you are using wrong context: enter image description here

Check the code below which can complete your task:

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
    title: 'Navigation Basics',
    home: FirstRoute(),
  ));
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('First Route'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Open route'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Second Route"),
        ),
        endDrawer: Builder(
          builder: (context) {
            return Container(
              width: 100,
              color: Colors.black,
              alignment: Alignment.center,
              child: GestureDetector(
                child: const Text(
                  "close drawer",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            );
          },
        ),
        body: Builder(builder: (context) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                ElevatedButton(
                  onPressed: () {
                    Scaffold.of(context).openEndDrawer();
                  },
                  child: const Text('open drawer'),
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('Go back!'),
                ),
              ],
            ),
          );
        }),
      ),
    );
  }
}
  • Related