Flutter Navigator.popUntil 参数传递
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在Flutter中,Navigator.popUntil
是一个用于关闭当前导航堆栈上所有指定路由之上的路由的方法。如果你想在使用 Navigator.popUntil
的时候传递数据,可以使用 ModalRoute.of
来获取当前路由的状态,并通过它来传递数据。
以下是一个简单的例子,演示如何在使用 Navigator.popUntil
的时候传递参数:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void _navigateAndPopUntil(BuildContext context, Widget predicate) {
Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return AnotherPage();
})).then((value) {
Navigator.of(context).popUntil(ModalRoute.withName(predicate.runtimeType));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: RaisedButton(
child: Text('Navigate and Pop Until'),
onPressed: () => _navigateAndPopUntil(context, AnotherPage()),
),
),
);
}
}
class AnotherPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Another Page'),
),
body: Center(
child: RaisedButton(
child: Text('Pop Until Home Page'),
onPressed: () => Navigator.of(context).pop('Data from AnotherPage'),
),
),
);
}
}
在这个例子中,我们创建了两个页面 MyHomePage
和 AnotherPage
。在 MyHomePage
中,我们定义了 _navigateAndPopUntil
方法,它推导了另一个页面,并在完成后使用 Navigator.popUntil
回到 MyHomePage
。在 AnotherPage
中,我们在 Navigator.pop
调用中传递了一个字符串 'Data from AnotherPage'
。
请注意,这种方式并不是 Navigator.popUntil
的直接参数传递,而是通过路由状态(ModalRoute
)来间接传递数据。如果你需要更复杂的参数传递,可能需要考虑使用 InheritedWidget
或者其他状态管理方案。
评论已关闭