在主函数main中创建routes.然后通过点击按钮实现页面跳转。
- 通过路由名跳转 2. 通过页面跳转
routes: <String, WidgetBuilder>{
'plugin': (BuildContext context) => PluginUse(),
'less': (BuildContext context) => LessGroupPage(),
'ful': (BuildContext context) => StatefulGroup(),
'layout': (BuildContext context) => LayoutPage(),
},
完整代码
import 'package:flutter/material.dart';
import 'package:untitled/inner_component.dart';
import 'package:untitled/layout_page.dart';
import 'package:untitled/plugin_use.dart';
import 'package:untitled/stateful_component.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('路由与导航使用'),
),
body: RouteNavigator(),
),
routes: <String, WidgetBuilder>{
'plugin': (BuildContext context) => PluginUse(),
'less': (BuildContext context) => LessGroupPage(),
'ful': (BuildContext context) => StatefulGroup(),
'layout': (BuildContext context) => LayoutPage(),
},
);
}
}
class RouteNavigator extends StatefulWidget {
@override
State<RouteNavigator> createState() => _RouteNavigatorState();
}
class _RouteNavigatorState extends State<RouteNavigator> {
bool navbyName = false;
@override
Widget build(BuildContext context) {
return Container(
child: ListView(
children: <Widget>[
SwitchListTile(
title: Text('${navbyName? '': '不'}通过路有名跳转'),
value: navbyName,
onChanged: (value){
setState(() {
navbyName = value;
});
}),
_item('Stateless组件', LessGroupPage(), 'less'),
_item('plugin插件使用', PluginUse(), 'plugin'),
_item('State组件', StatefulGroup(), 'ful'),
_item('layout组件', LayoutPage(), 'layout'),
]
),
);
}
_item(String label, page, String navName) {
return Container(
child: ElevatedButton(
onPressed: () {
if (navbyName) {
Navigator.pushNamed(context, navName);
} else {
Navigator.push(context, MaterialPageRoute(builder: (context) => page));
}
},
child: Text(label),
),
);
}
}
子组件appBar中增加返回按钮
appBar: AppBar(
title: Text('plugin使用'),
leading: GestureDetector(
onTap: (){
Navigator.pop(context);
},
child: Icon(Icons.arrow_back),
),
),