通过 VS Code 创建一个新的 Flutter 工程,创建好后,就会得到一个计数器应用的 Demo。在“计数器”示例的基础上,删掉多余部分,然后写自己需要的部分。
import 'package:flutter/material.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: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
],
),
),
);
}
}
利用Navigator.push的路由跳转:
在这个空的demo上创建一个新路由,命名“NewRoute”:
class NewRoute extends StatelessWidget {
const NewRoute({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("New route"),
),
body: const Center(
child: Text("This is new route"),
),
);
}
}
新路由继承自StatelessWidget,界面很简单,在页面中间显示一句"This is new route"。
在_MyHomePageState.build方法中的Column的子 widget 中添加一个按钮(RaisedButton)
RaisedButton(
child: const Text("open new route"),
color: Colors.blue,
textColor: Colors.white,
onPressed: () {
//导航到新路由
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const NewRoute();
}));
},
),
Navigator.push(BuildContext context, Route route):将给定的路由入栈(即打开新的页面),返回值是一个Future对象,用以接收新路由出栈(即关闭)时的返回数据。
路由传值:
创建一个TipRoute路由,让它接受一个提示文本参数