Equatable 在 Flutter Dart 中的使用

问题描述 投票:0回答:1

我目前正在从事 Flutter 学校项目。 我对 Flutter 和 Dart 完全陌生,很难理解 Equatable 包的用法。

我使用 Bloc-Pattern 构建 Flutter 应用程序。 在在线课程中,他们描述了 Equatable 的用法,以及它如何帮助使对象比较更加可靠。但由于可等值对象也需要是不可变的,我不明白如何使用这些对象。

我有以下场景。 在我的 Flutter 项目中,我有一个编辑视图可以更改,比如说 AccountInformations。帐户信息使用 Asp.Net 后端存储到数据库中。在Flutter中我调用服务来获取AccountInformation,这也是Flutter项目中的一个模型类。 AccountInformation 是 Equatable,因为我想将它与不同的 AccountInformation 对象进行比较。

现在我计划将 AccountInformation 对象的属性/变量绑定到编辑视图中的文本字段。但由于属性是最终的,我无法更改它们。

现在我只看到一个选项,有一个方法并根据“保存”上的文本字段创建一个新的 AccountInfo 对象,以将其写回数据库,或者不使 AccountInfo 为可用。

在我看来,这太复杂了,我很确定我错过了一个重要的部分。 您将如何在您的应用程序中实现以下场景?

感谢和问候!

flutter dart immutability equatable
1个回答
0
投票

您可以使用

copyWith
方法,使用
copyWith
方法是处理此类场景的好方法。它允许您创建具有更新属性的新对象,同时保持原始对象不可变。以下是如何在场景中使用
copyWith
的简短示例:

假设您有一个

AccountInformation
类,如下所示:

import 'package:equatable/equatable.dart';

class AccountInformation extends Equatable {

  const AccountInformation({
    required this.username,
    required this.email,
    required this.phoneNumber,
  });

  final String username;
  final String email;
  final String phoneNumber;

  @override
  List<Object?> get props => [username, email, phoneNumber];

  AccountInformation copyWith({
    String? username,
    String? email,
    String? phoneNumber,
  }) {
    return AccountInformation(
      username: username ?? this.username,
      email: email ?? this.email,
      phoneNumber: phoneNumber ?? this.phoneNumber,
    );
  }
}

使用

copyWith
类中定义的
AccountInformation
方法,您可以轻松创建具有更新属性的新实例。以下是如何在 Flutter 代码中使用它的示例:

// Assume you have an existing accountInfo object
AccountInformation oldAccountInfo = /* get the account info */;

// Create a new instance with updated properties
AccountInformation newAccountInfo = oldAccountInfo.copyWith(
  username: 'newUsername', // updated username
  email: 'newEmail',       // updated email
);

// Now you can use the newAccountInfo object to update the UI or send it back to the database

我希望这个解决方案有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.