My question is: How to observe changes on simple variable like String or num? I know that you can easy observe object like this:
observe(t, (e) => print ("Value changed"));
but How to do this on simple variable?
Dart objects have runtimeType property which returns Type . To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .
How to Declare Variable in Dart. We need to declare a variable before using it in a program. In Dart, The var keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned to the variable because Dart is an infer type language.
AVOID late variables if you need to check whether they are initialized. Dart offers no way to tell if a late variable has been initialized or assigned to. If you access it, it either immediately runs the initializer (if it has one) or throws an exception.
(This answer applies to Polymer.dart.)
The observe
package includes a wrapper for single observable values: ObservableBox
.
import 'package:observe/observe.dart';
import 'dart:async';
void main() {
ObservableBox myValue = new ObservableBox('hello');
myValue.changes.listen((List<ChangeRecord> records) {
PropertyChangeRecord record = records[0] as PropertyChangeRecord;
print('${record.field} changed, it is now ${myValue.value}');
});
new Timer.periodic(const Duration(seconds: 1), (t) {
myValue.value = new DateTime.now();
});
}
There is no way to observe a top-level or function-scope single string, boolean, int, or double without using ObservableBox.
If the string, boolean, int, or double is a field of a class, you can use ObservableMixin
and the @observable
annotation.
class Foo extends Object with ObservableMixin {
@observable String bar = '';
}
You can then get notified when an instance of Foo changes:
foo.changes.listen((List<ChangeRecord> records) {
// ...
});
Here is an example of the binding of a string value that is object attribute:
<!DOCTYPE html>
<html>
<head>
<title>index</title>
<script src="packages/polymer/boot.js"></script>
</head>
<body>
<template id="_template" bind>
<input type="text" value="{{name}}">
<p>The name is {{name}}</p>
</template>
<script type="application/dart" src="index.dart"></script>
</body>
</html>
import 'dart:html';
import 'package:polymer/polymer.dart';
class Person extends Object with ObservableMixin {
@observable
String name;
Person(this.name);
}
main() {
query("#_template").model = new Person('Bob');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With