Flutter状态管理插件riverpod_tachyon_plugin的使用

Flutter状态管理插件riverpod_tachyon_plugin的使用

Riverpod code generation powered by Tachyon

信息

该代码生成器产生的代码几乎与官方的 riverpod_generator 相同,但它是使用 tachyon 而不是 build_runner

安装

  1. 在你的项目的 pubspec.yaml 中添加:
dependencies:
  riverpod_annotation: any

dev_dependencies:
  tachyon: any
  riverpod_tachyon_plugin: any
  1. 创建一个名为 tachyon_config.yaml 的文件在项目根目录下:
file_generation_paths: # 哪些文件/路径需要包含在构建中
  - "file/path/to/watch"
  - "another/one"

generated_file_line_length: 80 # 默认行长度

plugins:
  - riverpod_tachyon_plugin # 注册 riverpod_tachyon_plugin

代码生成

现在你可以像使用 build_runner 一样创建提供者。主要的区别是你需要将部分文件更改为以下格式 <file name>.gen.dart

示例

import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'user.gen.dart';

class User {
  User({
    required this.id,
    required this.username,
  });

  final int id;
  final String username;
}

@riverpod
User user(UserRef ref) {
  return User(id: 11, username: 'pantelis');
}

执行 tachyon:

dart run tachyon build

这将生成以下代码:

part of 'user.dart';

String _$userHash() => r'0c59864fbc5f80cdab48302d3bd7c942c878cb87';

@ProviderFor(user)
final userProvider = AutoDisposeProvider<User>.internal(
  user,
  name: r'userProvider',
  debugGetCreateSourceHash:
      const bool.fromEnvironment('dart.vm.product') ? null : _$userHash,
  dependencies: null,
  allTransitiveDependencies: null,
);

typedef UserRef = AutoDisposeProviderRef<User>;

完整示例

文件结构

- example/
  - lib/
    - example.dart
    - user.gen.dart
    - user.dart

example/lib/example.dart

import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'example.gen.dart';

class User {
  User({
    required this.id,
    required this.username,
  });

  final int id;
  final String username;
}

@riverpod
User user(UserRef ref) {
  return User(id: 11, username: 'Pantelis');
}

// Keep alive provider
@Riverpod(keepAlive: true)
Future<List<User>> users(UsersRef ref) async {
  await Future.delayed(const Duration(seconds: 1));
  return [
    User(id: 11, username: 'Pantelis'),
  ];
}

class Post {
  Post({
    required this.id,
  });

  final int id;
}

@riverpod
class PostNotifier extends _$PostNotifier {
  @override
  Post build(int postId) {
    // Family provider
    return Post(id: postId);
  }
}

// Provider with dependencies
@Riverpod(dependencies: [user])
class PostsNotifier extends _$PostsNotifier {
  @override
  List<Post> build() {
    // get posts for user id
    ref.watch(userProvider).id;
    return [Post(id: 1)];
  }
}

example/lib/user.gen.dart

part of 'user.dart';

String _$userHash() => r'0c59864fbc5f80cdab48302d3bd7c942c878cb87';

@ProviderFor(user)
final userProvider = AutoDisposeProvider<User>.internal(
  user,
  name: r'userProvider',
  debugGetCreateSourceHash:
      const bool.fromEnvironment('dart.vm.product') ? null : _$userHash,
  dependencies: null,
  allTransitiveDependencies: null,
);

typedef UserRef = AutoDisposeProviderRef<User>;

example/lib/user.dart

import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'user.gen.dart';

class User {
  User({
    required this.id,
    required this.username,
  });

  final int id;
  final String username;
}

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

1 回复

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


当然,下面是一个关于如何使用 riverpod_tachyon_plugin 进行状态管理的 Flutter 代码示例。这个插件结合了 Riverpod 和 Tachyon,用于高效地管理 Flutter 应用中的状态。

首先,确保你已经在 pubspec.yaml 文件中添加了必要的依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_riverpod: ^1.0.0 # 请根据最新版本调整
  tachyon_dart: ^0.1.0 # 请根据最新版本调整
  riverpod_tachyon_plugin: ^0.1.0 # 请根据最新版本调整

然后,运行 flutter pub get 以获取这些依赖项。

接下来,让我们编写一个示例应用,展示如何使用 riverpod_tachyon_plugin 进行状态管理。

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tachyon_dart/tachyon_dart.dart';
import 'package:riverpod_tachyon_plugin/riverpod_tachyon_plugin.dart';

void main() {
  // 初始化 Tachyon
  Tachyon.init(TachyonConfig(enableLogging: true));

  // 创建 Riverpod 的 ProviderScope
  runApp(
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Riverpod Tachyon Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 使用 Tachyon Store 作为状态管理
    final counterStore = ref.watch(counterProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text('Riverpod Tachyon Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${counterStore.state}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 更新状态
          counterStore.increment();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

// 定义 Tachyon Store
class CounterStore extends Store<int> {
  CounterStore() : super(0);

  void increment() {
    setState((state) => state + 1);
  }
}

// 使用 Riverpod 定义 Provider
final counterProvider = Provider((ref) {
  return CounterStore();
}).autoDisposeWithTachyon<CounterStore>();

解释

  1. 依赖项和初始化:

    • pubspec.yaml 中添加 flutter_riverpod, tachyon_dart, 和 riverpod_tachyon_plugin 依赖项。
    • main 函数中初始化 Tachyon,并设置 enableLogging: true 以启用日志记录。
  2. ProviderScope:

    • 使用 ProviderScope 包装 MyApp,以确保 Riverpod 的 Provider 可以在整个应用中访问。
  3. ConsumerWidget:

    • MyHomePage 类继承自 ConsumerWidget,这使得它能够在 build 方法中访问 Riverpod 的 Provider。
  4. Tachyon Store:

    • CounterStore 类继承自 Store<int>,并包含一个 increment 方法来更新状态。
  5. Riverpod Provider:

    • 使用 ProviderautoDisposeWithTachyon 方法定义一个 counterProvider。这个 Provider 创建并管理一个 CounterStore 实例。
  6. UI 组件:

    • MyHomePage 中,使用 ref.watch(counterProvider) 获取当前的 CounterStore 实例,并显示其状态。
    • 使用 FloatingActionButton 来触发 CounterStoreincrement 方法,更新状态。

这个例子展示了如何将 riverpod_tachyon_plugin 结合 Riverpod 和 Tachyon 用于 Flutter 应用的状态管理。你可以根据需要扩展和修改这个示例。

回到顶部