Flutter自定义钩子插件get_hooks的使用

Flutter自定义钩子插件get_hooks的使用

Get Hooks 是一个简单的包,它为 GetView 小部件添加了一个定义,但具有 HookWidget 的功能。

class AnimatedHookWidget extends GetHookView<HomeController> {
  const AnimatedHookWidget({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    final animationController = useAnimationController(
      duration: const Duration(seconds: 5),
    );

    final animation = useAnimation(animationController);

    animationController.repeat(min: 0, max: 1);

    return Transform.rotate(
      angle: pi * animation * 2,
      child: const FlutterLogo(
        size: 100,
      ),
    );
  }
}

完整示例代码

import 'dart:math';

import 'package:example/app/modules/home/home_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:get/get.dart';
import 'package:get_hooks/get_hooks.dart';

import 'app/routes/app_pages.dart';

void main() {
  runApp(
    GetMaterialApp(
      title: "Get Hooks Example",
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      theme: ThemeData.dark(useMaterial3: true),
    ),
  );
}

class _BodyWidget extends GetHookView<HomeController> {
  const _BodyWidget();

  [@override](/user/override)
  Widget build(context) {
    final val = useState<bool>(controller.counter % 2 == 0);

    return Switch(
      value: val.value,
      onChanged: (v) => val.value = v,
    );
  }
}

class AnimatedHookWidget extends GetHookView<HomeController> {
  const AnimatedHookWidget({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    final animationController = useAnimationController(
      duration: const Duration(seconds: 5),
    );

    final animation = useAnimation(animationController);

    animationController.repeat(min: 0, max: 1);

    return Transform.rotate(
      angle: pi * animation * 2,
      child: const FlutterLogo(
        size: 100,
      ),
    );
  }
}

/// A spinning widget, used by the home view to demonstrate the use of
/// a controller within a hook view.
class SpinningWidget extends GetHookView<HomeController> {
  const SpinningWidget({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    // Animation controller initialized without having to use vsync
    final animationController = useAnimationController(
      duration: const Duration(seconds: 2),
    );

    // animation is used to change this widget's state then driven
    // to add a pleasing curve.
    final animation = useAnimation(
      animationController.drive(CurveTween(curve: Curves.easeInOut)),
    );

    // Tell the animation to endlessly repeat.
    animationController.repeat(min: 0, max: 1);

    // Return a transformation widget with an Obx object within to change
    // the state of the Text widget.
    return Transform.rotate(
      angle: pi * (animation * 2),
      child: Obx(() => Text(controller.counter.toString())),
    );
  }
}

更多关于Flutter自定义钩子插件get_hooks的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义钩子插件get_hooks的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


get_hooksGetX 状态管理库的一个扩展,它允许你在 Flutter 中使用类似 React Hooks 的方式来管理状态。通过 get_hooks,你可以更简洁地编写代码,并且更容易复用逻辑。

安装 get_hooks

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

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  get_hooks: ^0.4.0

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

基本用法

get_hooks 提供了几个常用的 Hooks,比如 useStateuseEffectuseMemo 等。下面是一个简单的例子,展示了如何使用 useStateuseEffect

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

class CounterExample extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final counter = useState(0);

    useEffect(() {
      print("Counter changed to ${counter.value}");
      return () {
        print("Counter is disposed");
      };
    }, [counter.value]);

    return Scaffold(
      appBar: AppBar(
        title: Text('Get Hooks Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${counter.value}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => counter.value++,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: CounterExample(),
  ));
}

解释

  1. useState: useState 用于在组件中声明状态。它返回一个 ValueNotifier,你可以通过 value 属性来访问和修改状态。

    final counter = useState(0);
    
  2. useEffect: useEffect 用于在组件挂载、更新或卸载时执行副作用操作。它接受一个回调函数和一个依赖项列表。当依赖项发生变化时,回调函数会被重新执行。

    useEffect(() {
      print("Counter changed to ${counter.value}");
      return () {
        print("Counter is disposed");
      };
    }, [counter.value]);
回到顶部