gpt4 book ai didi

dart - 观察聚合物 Dart 的包装

转载 作者:行者123 更新时间:2023-12-03 02:58:17 25 4
gpt4 key购买 nike

我试图使用observe包,而不必在模型中具有批注,而仅通过在 setter 中提高notifyPropertyChange,因此要进行测试,我进行了以下测试

import 'package:observe/observe.dart';
import 'dart:async';
import 'dart:math';
void main() {

var dummyWatchingModel = new DummyWatchingModel();
new Timer.periodic(new Duration(milliseconds:1000), (_){
//calls a function that set a random value to the property in the observable model
dummyWatchingModel.setModelProps();
});
}

class Model extends Observable{
int _x;
Model(this._x);

int get x=> _x;
void set x(int value){
_x = notifyPropertyChange(#_x, _x, value);
}
}

class DummyWatchingModel{
Model model = new Model(1);
final rng = new Random();
anotherModel(){

//watch for changes in model instance properties
this.model.changes.listen((List<ChangeRecord> records) {
for(ChangeRecord change in records){
print(change.toString());
}
});
}

//the callback for the timer to assign a random value model.x
setModelProps(){
model.x = rng.nextInt(100);
print('called...');
}
}

我正在使用引发 notifyPropertyChange的setter来更改Model实例中属性的值,但它从未侦听更改,任何想法为何?

最佳答案

我认为您想使用ChangeNotifier而不是Observable

我不确定notifyPropertyChange,但是对于Observable,通常需要调用dirtyCheck以获得有关更改的通知。

前一阵子我做了一个小例子来学习这两个如何工作:

import 'package:observe/observe.dart';

class Notifiable extends Object with ChangeNotifier {
String _input = '';

@reflectable
get input => _input;

@reflectable
set input(val) {
_input = notifyPropertyChange(#input, _input, val + " new");
}

Notifiable() {
this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
}
}

class MyObservable extends Observable {
@observable
String counter = '';

MyObservable() {
this.changes.listen((List<ChangeRecord> record) => record.forEach(print));
}
}

void main() {
var x = new MyObservable();
x.counter = "hallo";
Observable.dirtyCheck();

Notifiable notifiable = new Notifiable();
notifiable.input = 'xxx';
notifiable.input = 'yyy';
}

关于dart - 观察聚合物 Dart 的包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24276737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com