Flutter类字段管理插件class_fields的使用

Flutter类字段管理插件class_fields的使用

目的

当序列化到或从JSON进行反序列化时,你需要为映射中的键提供字段名作为String。字符串非常棒!… 只要确保格式正确,没有拼写错误,并且如果你更新了字符串,也别忘了在其他地方也更新相同的字符串!

class_fields 是一个库,它生成所有字段名,帮助你保持代码DRY(Don’t Repeat Yourself)和类型安全。class_fields 创建了一个可以在整个代码库中使用的单一引用点。

使用方法

依赖它

在你的 pubspec.yaml 文件中添加 class_fieldsclass_fields_annotation

# 注解属于依赖项,因为它们在你的代码中被使用
dependencies:
  class_fields_annotation: [recent_version]

# class_fields 仅用于生成代码,不会在你的代码库中使用
# 所以它属于开发依赖项
dev_dependencies:
  class_fields: [recent_version]
  # 需要使用 class_fields
  build_runner: [recent_version]
使用它
添加部分文件

在你的 Dart 文件中添加 part 语句:

part 'main.f.dart';
注解你的类

[@fields](/user/fields) 注解你的类:

[@fields](/user/fields)
class Person {
  const Person({
    required this.name,
    required this.age,
  });

  final String name;
  final int age;
}
运行构建运行器

运行 build_runner 来生成代码:

# 运行一次
flutter packages pub run build_runner build --delete-conflicting-outputs

# 运行并监听更改
flutter packages pub run build_runner watch --delete-conflicting-outputs
使用生成的代码

在你的代码中使用生成的字段:

// 生成的代码
class _$PersonFields {
  const _$PersonFields();

  final name = 'name';
  final age = 'age';
}

class Person {
  ...

  // 添加生成类的静态实例
  static const fields = _$PersonFields();
}

// 在你的代码中某处
final value = map[Person.fields.name];

map[Person.fields.name] = value;

完整示例

以下是一个完整的示例,展示了如何使用 class_fields 插件。

import 'package:class_fields_annotation/class_fields_annotation.dart';
import 'package:json_annotation/json_annotation.dart';

part 'main.f.dart';

[@fields](/user/fields)
class Example {
  const Example({
    required String name,
    required this.code,
    required this.description,
    required this.date,
    required this.price,
  }) : _name = name;

  final String _name;
  final int code;

  [@Field](/user/Field)('desc')
  final String description;
  final DateTime date;

  [@JsonKey](/user/JsonKey)(name: 'money')
  final double price;

  static const fields = _$ExampleFields();
}

更多关于Flutter类字段管理插件class_fields的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter类字段管理插件class_fields的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


class_fields 是一个 Flutter 插件,用于帮助开发者更高效地管理和生成 Dart 类中的字段。它通过注解和代码生成的方式,自动生成字段的 gettersettercopyWith 方法、toString 方法等,从而减少样板代码,提高开发效率。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 class_fields 插件的依赖:

dependencies:
  class_fields: ^1.0.0

dev_dependencies:
  build_runner: ^2.1.0

使用步骤

  1. 创建类并使用注解

    在你的 Dart 文件中,创建一个类并使用 [@ClassFields](/user/ClassFields) 注解来标记需要生成字段的类。

    import 'package:class_fields/class_fields.dart';
    
    [@ClassFields](/user/ClassFields)()
    class User {
      final String name;
      final int age;
    
      User({required this.name, required this.age});
    }
    
  2. 运行代码生成器

    在终端中运行以下命令来生成代码:

    flutter pub run build_runner build
    

    这将会生成一个与你的类同名的 .g.dart 文件,其中包含自动生成的代码。

  3. 使用生成的代码

    生成的代码将包含 gettersettercopyWith 方法、toString 方法等。你可以直接在你的项目中使用这些方法。

    例如,生成的 User 类可能会有如下代码:

    // user.g.dart
    // ignore_for_file: unnecessary_getters_setters
    
    class _$User {
      String _name;
      int _age;
    
      User({required String name, required int age})
          : _name = name,
            _age = age;
    
      String get name => _name;
      set name(String name) => _name = name;
    
      int get age => _age;
      set age(int age) => _age = age;
    
      User copyWith({String? name, int? age}) {
        return User(
          name: name ?? this.name,
          age: age ?? this.age,
        );
      }
    
      @override
      String toString() {
        return 'User(name: $name, age: $age)';
      }
    }
    

    你可以这样使用:

    void main() {
      var user = User(name: 'Alice', age: 30);
      print(user.name); // Alice
      print(user.age); // 30
    
      var newUser = user.copyWith(name: 'Bob');
      print(newUser.name); // Bob
      print(newUser.age); // 30
    
      print(user.toString()); // User(name: Alice, age: 30)
    }
    

高级用法

class_fields 插件还支持一些高级功能,例如:

  • 自定义字段名称:你可以通过 [@Field](/user/Field) 注解来指定字段的名称。
  • 忽略字段:你可以使用 [@ignore](/user/ignore) 注解来忽略某些字段,不生成对应的代码。
  • 自定义生成代码:你可以通过配置 build.yaml 文件来自定义生成的代码。

示例

import 'package:class_fields/class_fields.dart';

[@ClassFields](/user/ClassFields)()
class User {
  [@Field](/user/Field)('fullName')
  final String name;

  [@ignore](/user/ignore)
  final int age;

  User({required this.name, required this.age});
}
回到顶部