rrousselGit / flutter_hooks

React hooks for Flutter. Hooks are a new kind of object that manages a Widget life-cycles. They are used to increase code sharing between widgets and as a complete replacement for StatefulWidget.
MIT License
3.13k stars 179 forks source link

Custom Hook creation with class example is not clear. #307

Closed vetrivendhan48 closed 2 years ago

vetrivendhan48 commented 2 years ago

I am trying to create my own custom hook with many primary hooks (useState, useCallback, etc.) . But I am unable to write that with current example provided in the documentation. Since I am new to Flutter I don't have clue to implement my custom Hook.

Blogs explored

  1. Flutter official docs.
  2. Other blog - https://blog.logrocket.com/how-to-use-flutter-hooks/

I somehow figured a way to implement on my own, but I am getting type changed error.

My current snippet.

use_counter.dart

import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class CounterHookT {
  late ValueNotifier counter;
  // ignore: prefer_typing_uninitialized_variables
  late Function cachedFunction;

  CounterHookT(this.counter, this.cachedFunction);
}

class _CounterHook extends Hook<CounterHookT> {
  const _CounterHook();

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

class _CounterHookState extends HookState<CounterHookT, _CounterHook> {
  @override
  void initHook() {
    super.initHook();
    // Widget on mount
  }

  @override
  CounterHookT build(BuildContext context) {
    ValueNotifier counter = useState<int>(0);

    final cachedFunction = useCallback(() {
      counter.value++;
    }, [counter]);

    CounterHookT counterHook = CounterHookT(counter, cachedFunction);
    return counterHook;
  }

  @override
  void dispose() {}
}

CounterHookT useCounter() {
  const _counterHook = _CounterHook();
  return use(_counterHook);
}

Usage

main.dart

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

import './hooks/use_counter.dart';

class MyApp extends HookWidget {
  Widget build(BuildContext context) {
    final CounterHookT counter = useCounter();

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Title'),
        ),
        body: GestureDetector(
          // automatically triggers a rebuild of the Counter widget
          onTap: () => counter.cachedFunction(),
          child: Text(counter.counter.value.toString()),
        ),
      ),
    );
  }
}

void main(List<String> args) {
  runApp(MyApp());
}
rrousselGit commented 2 years ago

Hello!

This seems to be a duplicate of https://github.com/rrousselGit/flutter_hooks/issues/217. Using hooks within other hooks currently does not work