Skip to content

Installation and basic usage guide for Oref in Dart/Flutter

Installation

Oref provides two packages:

NameVersionDescription
orefPub VersionReactive core
oref_flutterPub VersionIntegration of Oref with Flutter

We use the following commands for installation:

bash
dart pub add oref
bash
flutter pub add oref_flutter

Or update your pubspec.yaml file:

yaml
dependencies:
  oref: latest
yaml
dependencies:
  oref_flutter: latest

Declaring Reactive State

To declare a reactive state, we use the ref() function

dart
final count = ref(0)
dart
final count = ref(context, 0)

ref() accepts parameters and returns a Ref<T> object wrapped with a .value property:

dart
void main() {
    final count = ref(0);

    print(count); // Ref<int>
    print(count.value); // 0

    count.value++;
    print(count.value); // 1
}
dart
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:

dart
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:

dart
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: