dart - 如何使用 Dart ChangeNotifier 类?

标签 dart

我正在探索 Dart 观察库中的 ChangeNotifier 类,以便在命令行应用程序中使用。但是,我有两个问题。

  1. List<ChangeRecord> 中报告的更改数量对象在每次更新记录时都会增量重复。看图片:

    enter image description here

  2. ChangeRecord 不允许仅检索新值。因此,我尝试改用 MapChangeRecord。但是,我不知道如何使用它。

这是我的示例代码供引用:

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));
}

最佳答案

每次执行此代码时

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

您在 notifying.change(e) 中添加新订阅

如果你改变它像

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));
}

它应该按预期工作

关于dart - 如何使用 Dart ChangeNotifier 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774215/

相关文章:

flutter - 如何从异步功能使用Future?

sqlite - 如何在SQFlite中插入POJO对象和列表

google-maps - 在google_maps包上使用minify时的Dart2JS编译器异常

android - 任务 ':app:checkReleaseDuplicateClasses' 执行失败。 flutter

dart - 接受具体类实例的方法

dart - Flutter Expansion Tile -- 标题颜色变化,尾随动画箭头颜色变化

flutter - 如何在 flutter 的行中获取选定的索引

flutter - Dart Flutter DevTools "Debugger"标签未显示

dart - ListView.builder 上的交替背景颜色

dart - 当项目的下一部分出现时,无限 CustomScrollView 向后滚动