如何使用 HookWidget 而不是 StatefulWidget?

时间:2021-06-01 21:48:23

标签: flutter dart flutter-packages

我正在尝试重构 this code 以使用 HookWidget:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ConfettiController _controllerCenter;

  @override
  void initState() {
    _controllerCenter =
        ConfettiController(duration: const Duration(seconds: 10));
    super.initState();
  }

  @override
  void dispose() {
    _controllerCenter.dispose();
    super.dispose();

我该怎么办?感谢帮助!

1 个答案:

答案 0 :(得分:0)

ConfettiController 创建自定义挂钩,然后在 HookWidget 中扩展 MyApp

示例:

confetti_hook.dart

import 'package:confetti/confetti.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

ConfettiController useConfettiController({required Duration duration}) {
  return use(_ConfettiControllerHook(duration: duration));
}

class _ConfettiControllerHook extends Hook<ConfettiController> {
  const _ConfettiControllerHook({
    required this.duration,
    List<Object?>? keys,
  }) : super(keys: keys);

  final Duration duration;

  @override
  _ConfettiControllerHookState createState() => _ConfettiControllerHookState();
}

class _ConfettiControllerHookState
    extends HookState<ConfettiController, _ConfettiControllerHook> {
  late final ConfettiController _controller =
      ConfettiController(duration: hook.duration);

  @override
  void didUpdateHook(_ConfettiControllerHook oldHook) {
    super.didUpdateHook(oldHook);

    if (hook.duration != oldHook.duration) {
      _controller.duration = hook.duration;
    }
  }

  @override
  ConfettiController build(_) => _controller;

  @override
  void dispose() => _controller.dispose();
}

ma​​in.dart

class MyApp extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final ConfettiController controllerCenter =
        useConfettiController(duration: const Duration(seconds: 10));
    ...
    ...
    ...
  }
}