引入
pubspec.yaml
dependencies:
get:
主页面
void main() {
runApp(GetMaterialApp(
initialRoute: '/home',/// 初始化路由
getPages: [
GetPage(name: '/home', page: () => HomePage()),
GetPage(name: '/other', page: () => OtherPage()),
],
));
}
class HomePage extends StatelessWidget {
const HomePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
/// 注入依赖
final RomeoController rmvc = Get.put(RomeoController());
return Container(
child: Scaffold(
appBar: AppBar(
title: Text('GetX-Demo-Home'),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(() => Text('${rmvc.count}')),/// 使用Obx包裹组件,当该组件使用的count发生改变时,会自动刷新该组件
ElevatedButton(
onPressed: () {
rmvc.pressed();
},
child: Icon(Icons.add)),
ElevatedButton(
onPressed: () {
Get.toNamed('/other',
arguments: {'name': 'turbo', 'age': 20});/// 使用路由跳转,arguments:Map 跳转时可以携带参数
},
child: Icon(Icons.navigation))
],
))));
}
}
controller 继承自GetxController
/// 集成自GetxController
class RomeoController extends GetxController {
var count = 0.obs;/// .obs
pressed() => count++;
}
otherPage
class OtherPage extends StatelessWidget {
final RomeoController vc = Get.find();/// Get.find() 你可以让Get找到一个正在被其他页面使用的Controller,并将它返回给你。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('otherPage'),
leading: GestureDetector(
child: Icon(Icons.ac_unit),
onTap: () {
Get.back(result: 'sssss');
},
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${vc.count}' +
Get.arguments['name'] +
' ' +
Get.arguments['age'].toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 50,
color: Colors.orange,
)),
ElevatedButton(
onPressed: () {},
child: Icon(Icons.archive),
),
],
),
),
);
}
}