flutter - 不可变或可变数据模型,应该用于设计Google表单,Google Doc等软件吗?

标签 flutter dart immutability

我们正在开发一种在Flutter中可以进行广泛写入和存储的软件。而且它还将支持撤消和重做功能。
目前,我们在不可变数据结构方面的经验为零。
在 flutter 的研究过程中,我想到了冻结软件包,用于不可变数据模型的代码生成器,这促使我理解了不可变数据集。但是使用不可变数据模型会带来各种挑战,例如-

  • 更新数据模型
  • 的深层嵌套子级
  • 即使在任何嵌套数据模型中进行微小更改(例如google doc中的字母更改),也要对整个数据进行深度复制,这会使我们的应用程序运行缓慢。
  • 我们计划保留同一模型的多个副本以支持撤消或重做,但这将占用最终用户大量的内存空间。
  • 最佳答案

    Updating of deeply nested children of the data model



    由于您使用的是Freezed,这应该不是问题。
    Freezed提供了一种内置机制来更新深层嵌套的变量

    https://github.com/rrousselGit/freezed#deep-copy

    例如,假设您具有:

    @freezed
    abstract class Company with _$Company {
      factory Company({String name, Director director}) = _Company;
    }
    
    @freezed
    abstract class Director with _$Director {
      factory Director({String name, Assistant assistant}) = _Director;
    }
    
    @freezed
    abstract class Assistant with _$Assistant {
      factory Assistant({String name, int age}) = _Assistant;
    }
    

    然后,而不是:

    Company company;
    
    Company newCompany = company.copyWith(
      director: company.director.copyWith(
        assistant: company.director.assistant.copyWith(
          name: 'John Smith',
        ),
      ),
    );
    

    你可以写:

    Company company;
    
    Company newCompany = company.copyWith.director.assistant(name: 'John Smith');
    

    Deep copying of whole data even on a minor change in any of the nested data model(Like a letter change in the google doc), would make our application slow.



    使用不变性时,很少有理由制作“深拷贝”。
    相反,它是执行的浅拷贝。

    要继续Company示例,请假定您具有:

    var company = Company(
      name: 'Google',
      director: Director(
        name: 'John',
      ),
    )
    

    然后,当您想更改公司名称时,只需要做:

    company = company.copyWith(name: 'Facebook');
    

    这样做时,不会重新创建Director。仅Company是有效的。

    因为Director是不可变的,所以很好。我们无法更改Director上的任何内容,因此即使两个对象使用相同的Director也没有冲突的风险。

    We were planning to keep multiple copy of the the same model for supporting the undo or redo, but this will take a lot of memory space of the end user.



    从上一点继续,您将存储的不是深拷贝,而是浅拷贝。

    因此最终,对内存的影响减少了很多。

    就像您提到的undo-redo一样,即使您没有使用不可变数据,也有可能仍然使用该内存。

    关于flutter - 不可变或可变数据模型,应该用于设计Google表单,Google Doc等软件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61946954/

    相关文章:

    scala - 为什么 Scala 集合中没有不可变的双链表?

    android - 如何使用 invokeMethod 从 Native 传递字符串数组到 flutter

    flutter - Dart Generators:为什么我得到的 'LibraryDirectiveImpl'类型不是 'Statement'类型的子类型

    flutter - 如何在 flutter 中应用MVC或设计模式?

    flutter - 我如何获取要在其他功能中使用的复选框值?

    javascript - 从 Dart 创建 js 对象

    Flutter:如何在底部、左侧和右侧同时具有边框半径和边框颜色

    html - 角度 Dart 单选按钮未绑定(bind)到模型

    java - build 者的最后障碍

    C# 和不可变性和只读字段……谎言?