Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Hooks Fetching Data using useEffect - setState() or markNeedsBuild() called during build

Currently exploring functional_widgets and flutter_hooks. Having same idea with reactjs I'm fetching data with the following code.

@hwidget
Widget homeScreen(BuildContext context) {
  TodoListProvider model = Provider.of<TodoListProvider>(context);
  useEffect(() {
    print('effect');
    model.fetchList();
    return () => {};
  }, []);
  return Scaffold(
    appBar: _buildAppbar(context, model),
    bottomNavigationBar: _buildBottomNav(context, model),
    floatingActionButton: _buildFloatingAction(context),
    body: PageTransitionSwitcher(
      duration: const Duration(milliseconds: 300),
      reverse: model.reverse,
      transitionBuilder: (
        Widget child,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return SharedAxisTransition(
          child: child,
          animation: animation,
          secondaryAnimation: secondaryAnimation,
          transitionType: SharedAxisTransitionType.horizontal,
        );
      },
      child: _getCurrentTab(model.currentIndex),
    ),
  );
}

I don't think this is the right way since it's throwing an error.enter image description here

like image 803
Jasper Bernales Avatar asked Jul 15 '20 08:07

Jasper Bernales


2 Answers

The issue with:

  useEffect(() {
    model.fetchList();
  }, []);

is that fetchList is called synchronously inside build and modify an ancestor widget, which is not good.

You can wrap the fetchList call in a microtask:

  useEffect(() {
    Future.microtask(() => model.fetchList());
  }, []);
like image 173
Rémi Rousselet Avatar answered Oct 19 '22 00:10

Rémi Rousselet


I know this question is old. But I hope my answer can help someone. I solved the problem by making the function call in the next frame

useEffect(() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      model.fetchList();
    }
}, []);

like image 6
Aimn Blbol Avatar answered Oct 19 '22 00:10

Aimn Blbol