Installation and basic usage guide for Oref in Dart/Flutter
Installation
Oref provides two packages:
Name | Version | Description |
---|---|---|
oref | Reactive core | |
oref_flutter | Integration of Oref with Flutter |
We use the following commands for installation:
dart pub add oref
flutter pub add oref_flutter
Or update your pubspec.yaml
file:
dependencies:
oref: latest
dependencies:
oref_flutter: latest
Declaring Reactive State
To declare a reactive state, we use the ref()
function
final count = ref(0)
final count = ref(context, 0)
ref()
accepts parameters and returns a Ref<T>
object wrapped with a .value
property:
void main() {
final count = ref(0);
print(count); // Ref<int>
print(count.value); // 0
count.value++;
print(count.value); // 1
}
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
final count = ref(context, 0);
return TextButton(
onPressed: () => count.value++,
child: Text('Count: ${count.value}'),
);
}
}
Declaring Reactive Collections
WIP
In development, please read our roadmap.
Fine-grained Rebuilding Flutter
For example, in the Counter code from the Declaring Reactive State example, when we update the value of count
, the entire Counter
Widget gets rebuilt. This is unnecessary, as we only need to rebuild the Text
.
It is recommended to use the Observer
Widget for optimization:
class Counter extends StatelessWidget {
const Counter({super.key});
@override
Widget build(BuildContext context) {
final count = ref(context, 0);
return TextButton(
onPressed: () => count.value++,
child: Observer(
builder: (_) => Text('Count: ${count.value}'),
),
);
}
}
When the internal value of count
updates, only the Text
will be rebuilt. However, Observer
is suitable for collecting multiple reactive values. For simple usage, we recommend the obs()
function:
class Counter extends StatelessWidget {
const Counter({super.key});
@override
Widget build(BuildContext context) {
final count = ref(context, 0);
return TextButton(
onPressed: () => count.value++,
child: count.obs((value) => Text('Count: ${value}')),
);
}
}
TIP
For more details about obs()
, please check Core → Observable.
There are multiple ways to implement fine-grained rebuild:
- Use
Observer
to wrap and observe reactive data. - Use
obs()
for observation. - Use
derived() - Derivation
to combine values.