Flutter引用管理插件simple_ref的使用

Flutter引用管理插件simple_ref的使用

Pub Star on Github License: MIT

Simple Ref

一个简单、轻量且自动释放的Flutter服务定位器引用库,支持覆盖。

安装

flutter pub add simple_ref

使用

导入包

import 'package:simple_ref/simple_ref.dart';

单例引用

final repositoryRef = Ref(() => Repository());

// 或者使用tear-off方式
final repositoryRef = Ref(Repository.new);

// 访问实例
final repository = repositoryRef();

// 覆盖
repositoryRef.overrideWith(() => MockRepository());

自动释放,将应用包裹在RefScope

runApp(
    const RefScope(
        child: MyApp(),
    ),
);

实现、扩展或混入Disposable并重写dispose方法

class Controller implements Disposable {
  final counter = ValueNotifier(0);

  [@override](/user/override)
  void dispose() {
    counter.dispose();
  }
}

创建自动释放引用

final controllerRef = Ref.autoDispose((_) => Controller());

访问实例

这可以通过Widget或引用通过controllerRef.of(context)controllerRef(context)来完成。

class CounterPage extends StatelessWidget {
    const CounterPage({super.key});

    [@override](/user/override)
    Widget build(BuildContext context) {
        final controller = controllerRef.of(context);
        return Text('${controller.counter.value}');
    }
}

覆盖它

你可以通过使用overrideWith来覆盖实例。这对于测试或初始化异步实例非常有用。在下面的例子中,所有对controllerRef.of(context)的调用都将返回MockController

controllerRef.overrideWith((context) => MockController());

示例代码

以下是一个完整的示例,包括一个计数器应用程序,展示了如何使用simple_ref插件。

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:simple_ref/simple_ref.dart';

class Controller implements Disposable {
  late final _count = ValueNotifier(0);

  // 我们将其暴露为可读的监听值,以便从外部无法更改。
  ValueListenable<int> get count => _count;

  void increment() => _count.value++;
  void decrement() => _count.value--;

  [@override](/user/override)
  void dispose() {
    _count.dispose();
  }
}

final countControllerRef = Ref.autoDispose((_) => Controller());

void main() {
  runApp(const RefScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Simple Ref 计数器'),
          centerTitle: true,
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        ),
        body: const Center(child: CounterText()),
        floatingActionButton: const Buttons(),
      ),
    );
  }
}

class CounterText extends StatelessWidget {
  const CounterText({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    final controller = countControllerRef.of(context);
    final theme = Theme.of(context);

    return ListenableBuilder(
      listenable: controller.count,
      builder: (_, __) {
        final count = controller.count.value;
        return Text('$count', style: theme.textTheme.displayLarge);
      },
    );
  }
}

class Buttons extends StatelessWidget {
  const Buttons({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    final controller = countControllerRef(context);

    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        FloatingActionButton(
          onPressed: controller.increment,
          child: const Icon(Icons.add),
        ),
        const SizedBox(height: 8),
        FloatingActionButton(
          onPressed: controller.decrement,
          child: const Icon(Icons.remove),
        ),
      ],
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中引用并使用simple_ref插件的代码示例。simple_ref是一个用于管理引用的插件,它可以帮助你更方便地在Flutter应用中传递和管理数据引用。

步骤 1: 添加依赖

首先,在你的pubspec.yaml文件中添加simple_ref依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_ref: ^最新版本号  # 请替换为实际最新版本号

然后运行flutter pub get来安装依赖。

步骤 2: 导入插件

在你的Dart文件中导入simple_ref插件:

import 'package:simple_ref/simple_ref.dart';

步骤 3: 使用SimpleRef管理引用

下面是一个简单的示例,展示如何使用SimpleRef来管理一个字符串引用:

import 'package:flutter/material.dart';
import 'package:simple_ref/simple_ref.dart';

void main() {
  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 创建一个SimpleRef实例来管理字符串引用
  final ref = SimpleRef<String>('Initial Value');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SimpleRef Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Value: ${ref.value}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 更新引用值
                ref.value = 'Updated Value';
                // 通知监听器值已更改(如果需要的话,simple_ref 默认会通知)
              },
              child: Text('Update Value'),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 添加依赖:在pubspec.yaml中添加simple_ref依赖。
  2. 导入插件:在需要使用simple_ref的Dart文件中导入它。
  3. 创建和管理引用
    • 使用SimpleRef<T>创建一个引用实例,初始值为'Initial Value'
    • 在UI中使用ref.value来显示当前值。
    • 通过按钮点击事件更新引用值。

这个示例展示了如何使用simple_ref来管理一个简单的字符串引用。你可以根据需要扩展这个示例,管理更复杂的数据结构或添加更多的功能。

回到顶部