skip to Main Content

I’m new to flutter and I want to implement the useEffect hook.

Here is my widget:

import 'dart:developer';

import 'package:flutter/material.dart';

class MarketRunnerChart extends StatefulWidget {
  const MarketRunnerChart({Key? key}) : super(key: key);

  @override
  State<MarketRunnerChart> createState() => _MarketRunnerChartState();
}

class _MarketRunnerChartState extends State<MarketRunnerChart> {
  @override
  Widget build(BuildContext context) {
    useEffect(() {
      log('okok');
    }, []);

    return Text("Some text");
  }
}

But I got the error The method 'useEffect' isn't defined for the type '_MarketRunnerChartState'.
enter image description here
When I remove the useEffect hook out of the build function and put it directly in the class I got error 'useEffect' must have a method body because '_MarketRunnerChartState' isn't abstract.
enter image description here
I’m used to work with React, but right now with flutter I can’t figure out how to implement that hook.

How am I supposed to do this ?

3

Answers


  1. try add

    import 'package:flutter_hooks/flutter_hooks.dart';

    on top of your class file

    Login or Signup to reply.
  2. import flutter hooks

    import 'package:flutter_hooks/flutter_hooks.dart';
    
    class MarketRunnerChart extends StatefulWidget {
        const MarketRunnerChart({Key? key}) : super(key: key);
    
        @override
        State<MarketRunnerChart> createState() => _MarketRunnerChartState();
    }
    
    class _MarketRunnerChartState extends State<MarketRunnerChart> {
        useEffect(() {
            print('your log');
        }, []);
    
        @override
        Widget build(BuildContext context) {
    
            return Text("Some text");
        }
    }
    
    Login or Signup to reply.
  3. You can follow the doc example, import flutter_hooks, extend the HookWidget.

    import 'package:flutter_hooks/flutter_hooks.dart';
    
    class Example extends HookWidget {
      const Example({Key? key, })
          : super(key: key);
    
      @override
      Widget build(BuildContext context) {
         //your variable/instance like to listen
        useEffect(() {
          log('okok');
        }, [...listenThisInstance...]);
        return Container();
      }
    }
    

    More about useEffect

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search