Hooked on Flutter Hooks
Published in
2 min readAug 15, 2020
Flutter Hooks help do away with Stateless and Stateful Widget boiler-plate.
Here’s an example that sets the hook version of the standard tab controller for tabs by calling the method useTabController(...);
A wee bit of magic sauce,
final _key = GlobalKey();
is used by the screen refresh repaint mechanism to identify the TabBarView widget. If you do not give the widget a key, any changes to ${_index.value}
will update the Text widgets, but the display repaint will not replace the old Text widgets with their newer refreshed versions, which hold the newly updated _index.value
unless a key is set key: _key
in TabBarView
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';void main() => runApp(MaterialApp(home: TabBarDemo()));class TabBarDemo extends HookWidget {
final List<Widget> list = [
Tab(icon: Icon(Icons.card_travel)),
Tab(icon: Icon(Icons.add_shopping_cart)),
Tab(icon: Icon(Icons.ac_unit)),
]; @override
Widget build(BuildContext context) {
final _controller = useTabController(initialLength: list.length);
final _index = useState(0);
final _key = GlobalKey(); _controller.addListener(() {
_index.value =…