flutter - Flutter 和 Getx:可观察到的发射如何变化
问题描述
当用户移动容器和用户停止触摸容器时,我有一个改变颜色的小条。我正在使用监听器小部件和函数 onPointerMove,它调用值为 true 的 GetxController 和值为 false 的 onPointerUp,因此容器的颜色根据控制器中的 RxBool 更改。
我的问题是:在调用 onPointerMove 时,RxBool 更改为真实值,但我不知道该值是否总是被发出,即使它是相同的,因为这样我的小部件每次都会重绘;或者如果值没有发出任何东西,因为它是相同的。
这是控制器
RxBool isPressing = false.obs;
void changeColor(bool i) => i ? isPressing.value = true : isPressing.value = false;
这是侦听器小部件
Listener(
onPointerMove: (PointerEvent e) => _touchController.changeColor(true),
onPointerUp: (PointerUpEvent e) => _touchController.changeColor(false),
.
.
.
children: [
Obx(() => Container(
height: 100,
width: 4,
decoration: BoxDecoration(
color: _touchController.isPressing.value ? primaryColor : Colors.white,
borderRadius: BorderRadius.circular(10),
),
)),
解决方案
如果你在 StatelessWidget 中打开 Container 并在 build 方法中打印一些东西,你可能会注意到当值相同时它没有发出。
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MainController _touchController = Get.put(MainController());
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Listener(
onPointerMove: (PointerEvent e) =>
_touchController.changeColor(true),
onPointerUp: (PointerUpEvent e) =>
_touchController.changeColor(false),
child: Obx(() => Box(
isPressing: _touchController.isPressing.value,
)),
),
);
}
}
class Box extends StatelessWidget {
final bool isPressing;
const Box({Key? key, required this.isPressing}) : super(key: key);
@override
Widget build(BuildContext context) {
print('re build');
return Container(
height: 100,
width: 100,
decoration: BoxDecoration(
color: isPressing ? Colors.white : Colors.red,
borderRadius: BorderRadius.circular(10),
),
);
}
}
class MainController extends GetxController {
RxBool isPressing = false.obs;
void changeColor(bool i) =>
i ? isPressing.value = true : isPressing.value = false;
}
推荐阅读
- node.js - Node.js:短路径命名对 SEO 友好吗?
- json - 如果使用powershell的键中有破折号(-),如何读取json中的值
- bash - 如何从外部访问“git submodule foreach”中使用的变量?
- c - C 数据格式重做
- javascript - 对象检测 javascript - 如何在视频上绘制检测边界
- android - 如果有超过 20 种口味,Firebase 不会与 android studio 同步
- c++ - 取出用户输入整数中的每个数字,并显示每个数字到它的十六进制值的转换?
- sql - 在 SQL Server 存储过程中迭代查询结果
- python - 如何为在 Windows 10 上运行 Python 2.7.5 的 IDLE 安装 PIP?
- reactjs - 在material-ui中将主要内容定位在appbars和drawers周围的正确方法是什么?