📦

Simplifying State Management with Flutter Hooks

Aug 9, 2024

Flutter Hooks Presentation Notes

Introduction

  • Flutter's design can lead to dissatisfaction with writing logic in widgets.
  • Introduction of Flutter Hooks to simplify state management and reduce boilerplate code.
  • Benefits: Less time on code maintenance, more time for personal life.

Getting Started with Flutter Hooks

  • Install the package: flutter pub add flutter_hooks
  • Replace StatefulWidget with StatelessWidget and convert it into a HookWidget.

What are Hooks?

  • Hooks are reusable pieces of code.
  • Can use predefined hooks or create custom ones.
  • Hooks must:
    • Be prefixed with "use"
    • Be called only in the build method of a widget.

Example of useEffect

  • useEffect takes:
    1. A function as the first parameter (similar to initState & dispose).
    2. A list of variables as the second parameter that triggers re-execution if changed.
  • Leaving the second parameter as an empty array makes it run only once.
  • Multiple instances of the same hook can run independently.

Basic Hook Examples

Text Editing Controller Hook

  • Automatically handles creating and disposing of TextEditingController.
  • Reduces boilerplate when dealing with input fields.
  • Similar hooks exist for TabController, PageController, and ScrollController.

useState Hook

  • Requires a generic argument for initial state.
  • Example: Toggling visibility with a boolean state.
  • useState acts as a value notifier.

Optimization Strategies

  • Extract deeper widget trees to prevent unnecessary rebuilds.
  • Use HookBuilder to isolate rebuilds.
  • useValueNotifier can manage state without immediate rebuild.

Advanced Hooks for API Access

Using useMemoized

  • For caching large objects between widget rebuilds.
  • Helps maintain separation of concerns by keeping API logic outside widgets.

Data Fetching Example

  • Use FutureBuilder with hooks for API calls.
  • Trigger data fetches with value notifiers and rebuild when state changes.

Animations with Hooks

  • Create and dispose of animation controllers more easily.
  • Example of a record button with animated shadow:
    • Define the animation controller and its parameters.
    • Use useMemoized to avoid recreation.
    • Manage recording state with hooks.

Timer and State Management

  • Use a TickerProvider to manage animations over time.
  • Avoid excessive rebuilds by controlling timing.
  • Use custom hooks to encapsulate logic for cleaner code.

Creating Custom Hooks

  • Custom hooks are easy to create by defining a function that returns the desired resource.
  • Allows reuse of logic across multiple widgets.

Conclusion

  • Flutter Hooks significantly reduce boilerplate code and improve readability.
  • Provides more efficient state management and encourages code reusability.