Flutter 状态管理之GetX库
warning:
这篇文章距离上次修改已过182天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage(this.title);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Obx(
() => Text(
'你点击了 ${Controller.count.value} 次',
style: TextStyle(fontSize: 30),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: Controller.increment,
tooltip: '增加',
child: Icon(Icons.add),
),
);
}
}
class Controller extends GetxController {
static Controller get instance => Get.find();
RxInt count = 0.obs;
void increment() => count.value++;
}
void main() {
runApp(GetMaterialApp(
home: MyHomePage('GetX 状态管理示例'),
// 初始化GetX
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => MyHomePage('GetX 状态管理示例')),
],
));
}
这段代码使用了GetX库来管理状态,其中MyHomePage
是一个无状态的Widget,它展示了当前点击次数,并且有一个用于增加点击次数的FloatingActionButton。Controller
类继承自GetxController,它使用RxInt
来管理点击次数的状态,并提供了一个increment
方法来增加点击次数。在main
函数中,我们初始化了GetX并设置了应用的首页。
评论已关闭