【问题标题】:How to Pop Drawer in Scaffold tree after Push推后如何在脚手架树中弹出抽屉
【发布时间】:2021-10-22 17:45:15
【问题描述】:

场景:从主页,用户可以使用屏幕上的弹性框列表或抽屉列表导航到第二页。

但是,问题是如果用户通过抽屉导航到第二页,然后弹回到上一个屏幕,抽屉将始终展开。

参考 Widget Inspector 图片,在脚手架树下有一个抽屉层,我知道这是因为 Navigator.push 而发生的。因此,一旦用户通过抽屉访问第二页并且一旦用户返回主屏幕,我如何弹出它,默认情况下将最小化抽屉。没有像目前发生的那样展开。

使用 Navigate.pushReplacementNamed 不起作用,因为 MaterialApp 的小部件树将被完全删除,因此用户无法使用 AppBar 上的后退图标返回上一屏幕。

谢谢。

Widget Inspector

【问题讨论】:

  • 在推送到新屏幕之前使用Navigator.of(context).pop(); 使用Navigator.push()
  • @Assassin 发布您的解决方案作为答案
  • @NMAA 请接受答案,所以这个问题可以认为是完整的。
  • 当然,我已经发布了答案@HarshvardhanJoshi

标签: flutter


【解决方案1】:

在推送到新屏幕之前使用Navigator.of(context).pop();Navigator.pop(context); 将解决问题

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

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

  static const appTitle = 'Drawer Demo';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: const Center(
        child: Text('My Page!'),
      ),
      drawer: Drawer(
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Text('Drawer Header'),
            ),
            ListTile(
              title: const Text('Screen 1'),
              onTap: () {
                 //close the drawer
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => YourScreen(),
                  ),
                );
              },
            ),
            ListTile(
              title: const Text('Screen 2'),
              onTap: () {
              
                //close the drawer
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => YourScreen2(),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

【讨论】:

    【解决方案2】:

    你可以使用:

     Navigator.pop(context);
    

    在你推动之前,或者做一个

    Navigator.of(context).pushReplacement(newRoute);
    

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多