在推送到新屏幕之前使用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(),
),
);
},
),
],
),
),
);
}
}