【问题标题】:How to use Dart ChangeNotifier class?如何使用 Dart ChangeNotifier 类?
【发布时间】:2013-12-25 15:20:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: dart


    【解决方案1】:

    每次执行这段代码

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

    您在notifiable.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));
    }
    

    它应该按预期工作

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2020-02-07
      • 2022-07-09
      • 2020-09-17
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多