flutter 基本路由跳转、传参、末尾浮动按钮组件FloatingActionButton
路由就是组件即dart文件
1、路由跳转
(1)在要跳转的dart文件中先导入被跳转的dart文件
(2)在回调函数中
(3)因为跳转的路由是单独的页面,所以没有主题样式,需要重新设置,即return配置Scaffold
跳转到指定路由:
Navigator.of(context).push(
MaterialPageRoute(
builder: (context)=>组件名()
)
);
回退到上一个路由:
Navigator.of(context).pop();
2、跳转传参数
无状态组件的路由
(1)通过构造函数指定参数
(2)在跳转的组件中:(context)=>组件名(传入参数)
有状态组件的路由
(1)第一个类通过构造函数指定参数并接收
(2)在第一个类中传入参数到第二个类
(3)第二个类通过构造函数指定参数并接收,虽然两个类是继承,但这里不能使用this获取父类的属性
3、末尾浮动组件
(1)该按钮组件固定位置在屏幕右下角
(2)在Scaffold中设置与appBar同级
floatingActionButton: FloatingActionButton(
child:组件,
tooltip:长按显示的内容,
onPressed: (){
...
},
),
//设置按钮位置
floatingActionButtonLocation:FloatingActionButtonLocation.endTop
代码示例:
路由待跳转文件
import 'package:flutter/material.dart';
//引入路由文件
import 'me.dart';
import 'search.dart';
class Home3 extends StatefulWidget {
Home3({ Key key}) : super(key: key);
@override
_Home3State createState() => _Home3State();
}
class _Home3State extends State<Home3> {
@override
Widget build(BuildContext context) {
return Container(
child:Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//按钮跳转
RaisedButton(child: Text("跳到search"),
color:Theme.of(context).accentColor,
onPressed:(){
//导航跳转
Navigator.of(context).push(
MaterialPageRoute(
builder: (context)=>Search(title:'哈哈哈')
)
);
}
),
SizedBox(height: 20,),
//按钮跳转
RaisedButton(child: Text("跳到Me"),
color:Theme.of(context).accentColor,
onPressed:(){
//导航回退
Navigator.of(context).push(
MaterialPageRoute(
builder: (context)=>Me(title: "哇咔咔")
)
);
}
),
],
),
);
}
}
有状态路由页面:
import 'package:flutter/material.dart';
class Me extends StatefulWidget {
//构造函数接收参数
String title='me';
Me({ this.title="表单"});
@override
//传递给第二个子类
_Home2State createState() => _Home2State(title2:this.title);
}
class _Home2State extends State<Me> {
//子类通过构造函数接收
String title2;
_Home2State({ this.title2='hh'});
@override
//这里虽然继承,但不能使用this获取父类的属性
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text(this.title2),),
body: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text("meeee"),
);
}
}
/* 单独的页面没有主题样式,需要通过Scaffold自行设置 */
无状态路由页面:
import 'package:flutter/material.dart';
class Search extends StatelessWidget {
String title;
//构造函数接收参数
Search({ this.title='SEARCCC'});
@override
Widget build(BuildContext context) {
return Scaffold(
//浮动按钮
floatingActionButton: FloatingActionButton(
child: Text('返回'),
onPressed: (){
//导航返回
Navigator.of(context).pop();
},
),
appBar: AppBar(title:Text(this.title)),
body:Home()
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text("searcheeee1"),
);
}
}
还没有评论,来说两句吧...