Flutter通过get更改int状态



我有一个简单的网站菜单,点击它只是更改int值,并根据int值更改字体颜色。

我不想用setState代替它。我需要用getX。我这样做就像

class SideMenu extends StatefulWidget {
const SideMenu({Key? key}) : super(key: key);
@override
_SideMenuState createState() => _SideMenuState();
}
class _SideMenuState extends State<SideMenu> {
TileColorX tcx = Get.put(TileColorX());
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
DrawerHeader(
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Dashboard ',
style: Theme.of(context).textTheme.caption!.copyWith(
color: Colors.white,
fontSize: 21,
fontWeight: FontWeight.w700)),
Text('Dashboard',
style: Theme.of(context).textTheme.caption!.copyWith(
color: primaryColor,
fontSize: 21,
fontWeight: FontWeight.w700)),
],
)),
),
DrawerListTile(
title: "Dashboard",
svgSrc: "assets/icons/menu_dashbord.svg",
control: 0,
press: () {
tcx.toggle(0);
},
),
DrawerListTile(
title: "POS and Invoices",
svgSrc: "assets/icons/menu_tran.svg",
control: 1,
press: () {
tcx.toggle(1);
},
),
],
),
);
}
}
class DrawerListTile extends StatelessWidget {
DrawerListTile({
Key? key,
// For selecting those three line once press "Command+D"
required this.title,
required this.svgSrc,
required this.press,
required this.control,
}) : super(key: key);
final String title, svgSrc;
final VoidCallback press;
final int control;
TileColorX tcx = Get.put(TileColorX());
@override
Widget build(BuildContext context) {
return ListTile(
onTap: press,
horizontalTitleGap: 0.0,
leading: SvgPicture.asset(
svgSrc,
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54,
height: 16,
),
title: Text(
title,
style: TextStyle(
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54),
),
);
}
}

我有一个切换的课程

class TileColorX extends GetxController {
RxInt selectedIndex = 0.obs;    
void toggle(int index) => selectedIndex.value = index;    
}

但它并没有改变状态(意味着不改变我的字体颜色(

您需要在想要看到更改的小部件上使用Obx。这将工作

return Obx(() => ListTile(
onTap: press,
horizontalTitleGap: 0.0,
leading: SvgPicture.asset(
svgSrc,
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54,
height: 16,
),
title: Text(
title,
style: TextStyle(
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54),
),
));

我不知道Obx到底做了什么,但它会为你工作:D

相关内容

最新更新