我有一个小条,当用户移动容器和用户停止触摸容器时,它会改变颜色。我正在使用侦听器小部件和 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),
),
)),
答案 0 :(得分:0)
如果你在 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;
}