如何在颤振抽屉中返回主页/主页
Posted
技术标签:
【中文标题】如何在颤振抽屉中返回主页/主页【英文标题】:how to return to home/main page in flutter drawer 【发布时间】:2020-05-06 00:22:14 【问题描述】:Flutter 有 findAncestorWidgetOfExactType(旧 Element.ancestorWidgetOfExactType),我想它可以用来返回主页面(在 MyHomePage 下面的示例中)。请帮助我如何在点击抽屉项目主页时导航到主页。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
DrawerOnly sameDrawerOnly = DrawerOnly();
class MyApp extends StatelessWidget
final appTitle = 'Drawer Demo';
@override
Widget build(BuildContext context)
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
class MyHomePage extends StatelessWidget
final String title;
MyHomePage(Key key, this.title) : super(key: key);
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: Text('My Page!')),
drawer: sameDrawerOnly,
);
class DrawerOnly extends StatefulWidget
const DrawerOnly (
Key key,
) : super(key: key);
@override
_DrawerOnlyState createState() => _DrawerOnlyState();
class _DrawerOnlyState extends State<DrawerOnly >
static int itemClicked = 0;
@override
Widget build(BuildContext ctxt)
return Drawer(
child: new ListView(
children: <Widget>[
new DrawerHeader(
child: new Text("DRAWER HEADER.."),
decoration: new BoxDecoration(
color: Colors.orange
),
),
new ListTile(
title: new Text("Item => A", style: itemClicked==1 ? TextStyle( fontWeight: FontWeight.bold, color: Colors.red.withOpacity(0.6) ) : null),
onTap: ()
Navigator.pop(ctxt);
setState(()
itemClicked=1;
);
Navigator.push(ctxt,
new MaterialPageRoute(builder: (ctxt) => new FirstPage()));
,
),
new ListTile(
title: new Text("Item => 2", style: itemClicked==2 ? TextStyle( fontWeight: FontWeight.bold , color: Colors.green.withOpacity(0.6) ) : TextStyle()),
onTap: ()
Navigator.pop(ctxt);
setState(()
itemClicked=2;
);
Navigator.push(ctxt,
new MaterialPageRoute(builder: (ctxt) => new SecondPage()));
,
),
new ListTile(
title: new Text("Home", style: itemClicked==3 ? TextStyle( fontWeight: FontWeight.bold , color: Colors.green.withOpacity(0.6) ) : TextStyle()),
onTap: ()
Navigator.pop(ctxt);
setState(()
itemClicked=3;
);
// how to get findAncestorWidgetOfExactType
,
),
],
)
);
class FirstPage extends StatelessWidget
@override
Widget build(BuildContext ctxt)
return new Scaffold(
drawer: sameDrawerOnly,
appBar: new AppBar(title: new Text("First Page"),),
body: new Text("I belongs to First Page"),
);
class SecondPage extends StatelessWidget
@override
Widget build(BuildContext ctxt)
return new Scaffold(
drawer: sameDrawerOnly,
appBar: new AppBar(title: new Text("Second Page"),),
body: new Text("I belongs to Second Page"),
);
还有另一个SO 帖子,但没有详细说明以帮助导航器通过查找祖先小部件返回主页。
【问题讨论】:
【参考方案1】:如果你想进入导航器的第一页,你可以这样做:
Navigator.of(context).popUntil((route) => route.isFirst)
您链接的帖子适用于您使用命名路线时:
Navigator.popUntil(context, ModalRoute.withName('/'))
【讨论】:
以上是关于如何在颤振抽屉中返回主页/主页的主要内容,如果未能解决你的问题,请参考以下文章