flutter - Flutter: how to listen to a int change?
问题描述
I am trying to run a timer function and when the timer value reached a particular value i need to trigger another function. so i need to listen to the value change in the int start
import 'dart:async';
class CustomTimer{
Timer _timer;
int start = 0;
void startTimer(){
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(oneSec, (Timer timer){
start++;
print('start value $start');
});
}
void cancelTimer()
{
_timer.cancel();
}
}
I am calling this function from another class, How can i do that?
解决方案
You should be implement below way
class CustomTimer {
Timer _timer;
int start = 0;
StreamController streamController;
void startTimer() {
const oneSec = Duration(seconds: 1);
streamController = new StreamController<int>();
_timer = Timer.periodic(oneSec, (Timer timer) {
start++;
streamController.sink.add(start);
print('start value $start');
});
}
void cancelTimer() {
streamController.close();
_timer.cancel();
}
}
Other class when you listen updated value
class _EditEventState extends State<EditEvent> {
CustomTimer customTimer = new CustomTimer();
@override
void initState() {
customTimer.startTimer();
customTimer.streamController.stream.listen((data) {
print("listen value- $data");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container()
);
}
@override
void dispose() {
customTimer.cancelTimer();
super.dispose();
}
}
Here, I have created on streambuilder for listen int value
推荐阅读
- javascript - 刷新每 60 秒上传到特定位置的图像(相同的文件名)
- xamarin.forms - 如何在 xamarin 中为 Android 移动应用程序启用拖放功能?
- python - Django 使用 uuid 进行销售交易是否正确
- react-native - MobX React 替换 componentWillReact() 以触发布局动画
- php - 如何在 Laravel 中将数组数据从控制器传递到刀片
- javascript - 如何在 RichEmbed/MessageEmberd 中发送 gif
- php - Wordpress cookie 只能从一个页面获得,即使它是为整个域设置的
- python - ERROR:process_reader_win.cc(123)] NtOpenThread: {Access Denied} 尝试使用 Selenium 在 Python 上运行图像下载器
- trust - 如何在两个 freeIPA 实例之间设置跨领域信任
- python - Why GUI should use call_soon_threadsafe() when talking to asyncio loop