Flutter Hooks is a popular package in the Flutter community that introduces a new way to manage the lifecycle and state of Flutter widgets. Among its features, it provides hooks for various controllers, such as useTabController, useScrollController, usePageController, and useAnimationController. These hooks not only simplify the management of these controllers but also automatically handle their disposal, making the code cleaner and more efficient.

useTabController

Widget build(BuildContext context) {
  final tabController = useTabController(initialLength: 3);
  return Scaffold(
    appBar: AppBar(
      bottom: TabBar(
        controller: tabController,
        tabs: [
          Tab(icon: Icon(Icons.directions_car)),
          Tab(icon: Icon(Icons.directions_transit)),
          Tab(icon: Icon(Icons.directions_bike)),
        ],
      ),
    ),
    body: TabBarView(
      controller: tabController,
      children: [
        Icon(Icons.directions_car),
        Icon(Icons.directions_transit),
        Icon(Icons.directions_bike),
      ],
    ),
  );
}

The useTabController hook is used for managing tab navigation in a TabBar. It automatically disposes the TabController when the widget is removed from the widget tree.

useScrollController

Widget build(BuildContext context) {
  final scrollController = useScrollController();
  return ListView.builder(
    controller: scrollController,
    itemCount: 100,
    itemBuilder: (BuildContext context, int index) {
      return ListTile(title: Text('Item $index'));
    },
  );
}

useScrollController is used for managing scrollable widgets. It automatically disposes of the ScrollController to prevent memory leaks.

usePageController

Widget build(BuildContext context) {
  final pageController = usePageController();
  return PageView(
    controller: pageController,
    children: <Widget>[
      Center(child: Text('First Page')),
      Center(child: Text('Second Page')),
      Center(child: Text('Third Page')),
    ],
  );
}

The usePageController hook is for controlling pages in a PageView. Like other hooks, it handles the lifecycle of the PageController.

useAnimationController

Widget build(BuildContext context) {
  final animationController = useAnimationController(duration: const Duration(seconds: 2));
  return FloatingActionButton(
    onPressed: () {
      if (animationController.isAnimating) {
        animationController.stop();
      } else {
        animationController.repeat();
      }
    },
    child: AnimatedIcon(
      icon: AnimatedIcons.play_pause,
      progress: animationController,
    ),
  );
}

useAnimationController simplifies the creation and management of AnimationController instances. It disposes of the controller when the widget is no longer needed.

By using these hooks, developers can write more concise and readable code, and also avoid common pitfalls related to managing the lifecycle of controllers in Flutter.

Happy coding! 😊

Categorized in: