Flutter Hooks – useEffect, useState

 

useEffect :

We have implemented useEffect using flutter hooks and tried to replace the usage of init state and dispose in this part of the tutorial these two components are part  of lifecycle of widget.

In this part of the tutorial we will try to update the counter automatically with the help of Timer where we will replace the initialization and dispose phase of the controllers with hooks.

useEffect is called on every build call i..e, only once and if there are any keys specified in the constructor which are updated then the useEffect can be called multiple times based on changes.

This component accepts a function and returns a function usually subscribes to a stream and disposes it once finished.

Go through the previous blog for basic related to flutter hooks detailed explanation with video tutorial.

 

 

pubspec.yaml:

Add flutter hooks dependency to make use of useEffect and useState i.e., hooks concepts in your flutter app.

dependencies:
  flutter:
    sdk: flutter

  flutter_hooks: ^0.18.3

 

 

main.dart :

In this example we will try to skip init and dispose blocks and useEffect to initialize and dispose the timer once its used.This will be much efficient in memory leaks handling.

class _HomeState extends State<Home> {

  late Timer _timer;
  int _count = 0;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(Duration(seconds: 1), (abc) {
      setState(() {
        _count = abc.tick;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(child: Text("$_count",style: TextStyle(fontSize: 50.0),));
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }
}

class HooK extends HookWidget {
   HooK({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final _count = useState(0);

    useEffect((){
      final timer = Timer.periodic(Duration(seconds: 1), (timer) {
        _count.value = timer.tick;
      });
      return timer.cancel;
    },[]);

    return Center(child: Text("${_count.value}",style: TextStyle(fontSize: 50.0),));
  }
}

 

 

If you have any query’s in this part of the tutorial do let us know in the comment section below.

 

Show Buttons
Hide Buttons
Read previous post:
Flutter Hooks – Say no to Statefullwidget

  Flutter Hooks : Flutter Hooks concept is explained in this part of the tutorial considering a simple counter example...

Close