foreword
Learning Tutorial: Getx Tutorial_Flutter+Getx Series Practical Tutorials
Introduction
getX is a third-party state management plug-in. It not only has the function of state management, but also has functions such as routing management, theme management, international multilingual management, network request, and data verification. Compared with other state management components, getX is simple and powerful.
Official documentation
https://pub-web.flutter-io.cn/packages/get
Install
flutter pub add get
will be MaterialApp
modified toGetMaterialApp
GetMaterialApp(
title: 'getx',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'getx'),
);
Dialog、snackbar、bottomSheet
Dialog
ElevatedButton(
onPressed: () {
Get.defaultDialog(
title: "默认弹窗",
middleText: '弹出内容,你确定要卸载吗?',
confirm:
TextButton(onPressed: () {
Get.back();
}, child: const Text("确定")),
cancel:
TextButton(onPressed: () {
Get.back();
}, child: const Text("取消")));
},
child: const Text("getx 默认dialog"))
snack bar
ElevatedButton(
onPressed: () {
Get.snackbar("提示", "删除成功");
},
child: const Text("snack-bar"))
bottomSheet
ElevatedButton(
onPressed: () {
Get.bottomSheet(Container(
color: Colors.white,
height: 130,
child: Column(
children: [
ListTile(
leading: const Icon(Icons.wb_sunny_outlined),
title: const Text("白天模式"),
onTap: () {
Get.changeTheme(ThemeData.light());
Get.back();
},
),
const Divider(),
ListTile(
leading: const Icon(Icons.wb_sunny),
title: const Text("夜间模式"),
onTap: () {
Get.changeTheme(ThemeData.dark());
Get.back();
},
),
],
),
));
},
child: const Text("snack-bar"))
routing management
GetX
It is encapsulated for us Navigation
, no need context
to jump. It is easier to use GetX
routing jumps. You only need to use Get.to()
to perform routing jumps, GetX
which simplifies jump animation settings, animation duration definitions, and animation curve settings for routing jumps
We can Get.to()
realize ordinary routing jumps, by Get.toNamed
realizing named routing jumps, by Get.back()
realizing returning to the upper level routing, and by Get.ofAll()
returning to following routes, we can Get.off()
remove the current page from the page stack and add new pages to the page In the stack, you can Get.arguments
pass parameters by getting the route
Configure routing and routing animation
GetMaterialApp(
title: 'getx',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
// home 和 initialRoute同时存在的话initialRoute会优先生效
home: const MyHomePage(title: 'getx'), // 主页
initialRoute: '/', // 默认显示的路由页面
defaultTransition: Transition.leftToRight, // 设置所有页面默认的路由跳转动画
getPages: [
//路由地址
GetPage(name: '/', page: () => const MyHomePage(title: 'getx')),
GetPage(
name: '/my',
page: () => const MyInfo(),
transition: Transition.leftToRight // 设置路由过度动画
)
],
)
Get.toNamed('my', arguments: {
"message": 'Hello Flutter'});
Widget build(BuildContext context) {
String mes = Get.arguments?["message"] ?? '11';
return Scaffold(
appBar: AppBar(
title: const Text('我的'),
),
body: Center(
child: Text("个人信息:$mes"),
),
);
}
Route Extraction
import 'package:test/page/my.dart';
import 'package:get/get.dart';
class AppPage {
static final List<GetPage<dynamic>> routes = [
GetPage(
name: '/my',
page: () => const MyInfo(),
transition: Transition.leftToRight // 设置路由过度动画
)
];
}
GetMaterialApp(
title: 'getx',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
// home 和 initialRoute同时存在的话initialRoute会优先生效
home: const MyHomePage(title: 'getx'), // 主页// 默认显示的路由页面
defaultTransition: Transition.leftToRight, // 设置所有页面默认的路由跳转动画
getPages: AppPage.routes,
)
Routing middleware (routing guard)
import 'package:flutter/cupertino.dart';
import 'package:test/page/my.dart';
import 'package:get/get.dart';
class AppPage {
static final List<GetPage<dynamic>> routes = [
GetPage(
name: '/my',
page: () => const MyInfo(),
transition: Transition.leftToRight, // 设置路由过度动画
middlewares: [MyMiddleWare()])
];
}
// 中间件
class MyMiddleWare extends GetMiddleware {
// 重写重定向
redirect(route) {
String power = Get.arguments?['power'];
if (power == 'no') {
Get.snackbar("提示", "请先进行登录");
return const RouteSettings(name: 'login');
}
// 放行,跳转到目标路由
return null;
}
}
state management
It is mainly used to share state with multiple pages. When the state of a certain page changes, other pages also change accordingly.
Single Page State Management
class _MyHomePageState extends State<MyHomePage> {
// 定义一个响应式的整数
RxInt count = 0.obs;
// 或者
RxInt a = RxInt(0);
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
// const Color(0x00cab6ec)
body: Column(
children: [
ElevatedButton(
onPressed: () {
count.value += 1;
},
child: const Text("加1")),
// 监听值的变化
Obx(() => Text("当前值:${
count.value}"))
],
),
);
}
}
If you have used it vue3
, it is very easy to accept it.
Advantages: If you use setState
will re-run build
to update, if the content is too much, it will generate a large overhead. Implement a partial update by Getx
only updating the components you listen to.
Multi-page state management
Define a Controller
import 'package:get/get.dart';
class CountController extends GetxController {
// 定义响应式变量
RxInt count = 0.obs;
// 增加
void add() {
count.value++;
// 调用GetxController内置方法进行更新
update();
}
// 减少
void del() {
count.value--;
// 调用GetxController内置方法进行更新
update();
}
}
main page use
class _MyHomePageState extends State<MyHomePage> {
// 创建控制器示例
CountController countController =
Get.put(CountController(), tag: 'countController');
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
// const Color(0x00cab6ec)
body: Column(
children: [
ElevatedButton(
onPressed: () {
Get.toNamed('/my');
},
child: const Text("我的")),
ElevatedButton(
onPressed: () {
// 加1
countController.add();
},
child: const Text("加1")),
// 监听值的变化
Obx(() => Text("当前值:${
countController.count.value}"))
],
),
);
}
}
Other pages use
class MyInfoState extends State<MyInfo> {
// 获取示例
late final CountController countController;
void initState() {
super.initState();
countController = Get.find(tag: 'countController');
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('我的'),
),
body: Center(
child: ElevatedButton(
child: const Text("减1"),
onPressed: () {
countController.del();
},
),
),
);
}
}
GetX Binding
When we all use Getx
the state manager, we need to manually create an example, which is troublesome. Using Binding can uniformly initialize the state managers that need to be used when the project is initialized.
Several ways to create examples
Get.put
, without using a controller instance will also be createdGet.lazyPut
, creating an instance in a lazy loading manner, which will only be created when it is usedGet.putAsync
,Get.put
the asynchronous version ofGet.create
, a new instance is created each time it is used
Create binding class
import 'package:get/get.dart';
import 'count_controller.dart';
class AllControllerBinding implements Bindings {
void dependencies() {
// 初始化
Get.lazyPut<CountController>(() => CountController());
// 多个则多执行几次Get.lazyPut
}
}
Initialize in main.dart
GetMaterialApp(
title: 'getx',
// 初始化绑定状态管理类
initialBinding: AllControllerBinding(),
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
// home 和 initialRoute同时存在的话initialRoute会优先生效
home: const MyHomePage(title: 'getx'), // 主页// 默认显示的路由页面
defaultTransition: Transition.leftToRight, // 设置所有页面默认的路由跳转动画
getPages: AppPage.routes,
)
After
the initialization is completed, there is no need to create it again. When using it, you only need to Get.find
get the instance by
CountController countController = Get.find<CountController>();
GetView
GetView
Is GetX
an important component in the framework, it is mainly used to simplify the creation and management of page components. Through inheritance GetView
, you can easily create a page with state management and routing navigation functions.
The main functions of GetView are as follows:
-
Simplify page creation:
GetView
After inheritance, you only need to rewrite the method to create the page, no need to create orWidget build(BuildContext context)
manually .StatefulWidget
StatelessWidget
-
Management page status:
GetView
internally encapsulatesGetX
the status management function provided by the framework, which can easily monitor, update and destroy the status, avoiding the cumbersome operations of manual status management. -
Routing navigation:
GetView
Provides a simple routing navigation function, you can use methods such asGet.to()
, ,Get.off()
etc. to jump to the page, and you can pass parameters. -
Dependency injection:
GetView
Built-in dependency injection function, you can register and obtain global dependency objects through methods such asGet.put()
,Get.lazyPut()
etc., which are convenient for use in pages.
In general, GetView
the function is to simplify the creation and management of page components, provide convenient state management and routing navigation functions, so that developers can focus more on the realization of business logic.
example
// 需要指定要使用的状态管理类
class MyInfoPage extends GetView<CountController> {
const MyInfoPage({
super.key});
Widget build(BuildContext context) {
// 如果第一次使用还需要put(没有结合Binding时)
Get.put(CountController());
return Scaffold(
appBar: AppBar(
title: const Text('我的'),
),
body: Center(
child: ElevatedButton(
child: const Text("减1"),
onPressed: () {
// 因为几次了GetView并且指定了泛型,因此可以获取到对应controller
controller.del();
},
),
),
);
}
}
Several use cases:
- Simply display the shared state or need to operate on the shared state
- There are both shared state and private state, which can be used in combination with reactive state variables. This eliminates the need to create
StatefulWidget
and its correspondingState
multilingual configuration
Slightly, you can watch the video by yourself.
Tool class - GetUtils
GetUtils
It is Getx
a tool class library provided, including whether the value is empty, whether it is a number, video, audio, ppt, email, mobile phone number, etc.