本文是基于官方最新稳定版本 get: ^4.5.1
来进行开发。
通过阅读本文,你将学会如下:
1. 在 pubspec.yaml
文件中添加 GetX
的依赖,如下:
dependencies:
flutter:
sdk: flutter
get: ^4.5.1
2. 需要对 GetX
进行初始化,将默认的 MaterialApp
替换为 GetMaterialApp
即可,如下:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
Dialog 底层其实是对 AlertDialog 进行了封装, 一般用于二次确认的弹出框,比如当点击某个按钮提交资料时,需要用户二次确认,以防止误操作。
import 'package:flutter/material.dart';
import 'package:get/get.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 GetMaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('GetX 对话框基本使用'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: (){
Get.defaultDialog(onConfirm: () => print("Ok"), middleText: "Dialog made in 3 lines of code");
},
child: Text("显示 Dialog"),
),
],
),
)
)
);
}
}
如果想在应用程序中触发某些特定的事件后,需要弹出一则快捷消息,那么使用 Snackbar 则是最佳的选择,接下来我们看一下 GetX 如何来联调 Snackbar 来使用。
import 'package:flutter/material.dart';
import 'package:get/get.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 GetMaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('GetX 对话框基本使用'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: (){
Get.snackbar("Snackbar 标题", "欢迎使用Snackbar");
},
child: Text("显示 Snackbar"),
),
],
),
)
)
);
}
}
BottomSheet 是底部弹出的一个组件,常用于单选、验证码二次校验弹窗等,GetX 的 BottomSheet 底部弹出是自定义通过路由push 的方法实现底部弹窗的一个效果。
import 'package:flutter/material.dart';
import 'package:get/get.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 GetMaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('GetX 对话框基本使用'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: (){
Get.bottomSheet(
Container(
child: Wrap(
children: <Widget>[
ListTile(leading: Icon(Icons.music_note), title: Text('Music'), onTap: () => {}),
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video'),
onTap: () => {},
),
],
),
),
backgroundColor: Colors.white);
},
child: Text("BottomSheets"),
),
],
),
)
)
);
}
}