普通路由
Navigator.push()
与 Navigator.pop()
限制太多,不推荐使用
路由表
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
routes: {
"/": (context) => FirstWidget(),
"second": (context) => SecondWidget()
},
));
class FirstWidget extends StatefulWidget {
@override
_FirstWidgetState createState() => _FirstWidgetState();
}
class _FirstWidgetState extends State<FirstWidget> {
var _text = "0";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("First"),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_text),
RaisedButton(
child: Text("Click me"),
onPressed: () async {
var result = await Navigator.pushNamed(context, "second",
arguments: _text);
setState(() {
_text = result;
});
},
)
],
),
),
);
}
}
class SecondWidget extends StatelessWidget {
SecondWidget({Key key});
@override
Widget build(BuildContext context) {
var _text = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text("Second"),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(_text),
RaisedButton(
child: Text("Click me"),
onPressed: () =>
Navigator.pop(context, (int.parse(_text) + 1).toString()),
)
],
),
),
);
}
}
onGenerateRoute 路由钩子
相比于命名路由,可以多做一些相关的拦截
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
onGenerateRoute: (settings) {
var name = settings.name;
var args = settings.arguments;
// Do something here
switch (name) {
case '/':
return MaterialPageRoute(builder: (context) => FirstWidget());
case "second":
return MaterialPageRoute(builder: (context) => SecondWidget(args));
default:
return MaterialPageRoute(builder: (context) => BlankWidget());
}
},
));
class FirstWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text("Click me"),
onPressed: () => Navigator.pushNamed(context, "second",
arguments: DateTime.now().microsecondsSinceEpoch.toString()),
)),
);
}
}
class SecondWidget extends StatelessWidget {
final String _text;
SecondWidget(this._text);
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text(_text),
onPressed: () => Navigator.pushNamed(context, "not_exists"),
),
);
}
}
class BlankWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
);
}
}