Nawaf Alsulami
Nawaf Alsulami

Reputation: 719

How to use Dart ChangeNotifier class?

I'm exploring the ChangeNotifier class in Dart's observe library for use in a commandline application. But, I'm having two issues.

  1. The number of reported changes in a List<ChangeRecord> object are incrementally repeated in each update to the record. See image:

    enter image description here

  2. ChangeRecord doesn't allow for retrieving only new values. Thus, I'm trying to use a MapChangeRecord instead. But, I don't know how to use it.

This is my sample code for reference:

import 'dart:io';
import 'dart:async';
import 'dart:convert';
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);
  }
  
  void change(String text) {
    input = text;
    this.changes.listen((List<ChangeRecord> record) => print(record.last));
  }
}

void main() {
  Notifiable notifiable = new Notifiable();
  Stream stdinStream = stdin;
  stdinStream
    .transform(new Utf8Decoder())
      .listen((e) => notifiable.change(e));
}

Upvotes: 2

Views: 3035

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657238

each time this code is executed

stdinStream
    .transform(new Utf8Decoder())
      .listen((e) => notifiable.change(e));

you add a new subscription in notifiable.change(e)

If you change it like

import 'dart:io';
import 'dart:async';
import 'dart:convert';
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);
  }

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

  void change(String text) {
    input = text;
  }
}

void main() {
  Notifiable notifiable = new Notifiable();
  Stream stdinStream = stdin;
  stdinStream
    .transform(new Utf8Decoder())
      .listen((e) => notifiable.change(e));
}

it should work as expected

Upvotes: 3

Related Questions