【问题标题】:Flutter Hooks Fetching Data using useEffect - setState() or markNeedsBuild() called during buildFlutter Hooks 使用 useEffect 获取数据 - 在构建期间调用 setState() 或 markNeedsBuild()
【发布时间】:2020-11-04 16:37:31
【问题描述】:

目前正在探索functional_widgets 和flutter_hooks。与 reactjs 有相同的想法,我正在使用以下代码获取数据。

@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),
    ),
  );
}

我认为这不是正确的方法,因为它会引发错误。

【问题讨论】:

  • return () =&gt; {} 可能并不像您认为的那样。您将返回一个函数,该函数在调用时返回一个空 Map。我认为你的意思是return () {}。请记住,它是箭头或身体块。不是都。 :)

标签: flutter flutter-widget flutter-hooks


【解决方案1】:

问题:

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

fetchList在构建和修改祖先小部件内部同步调用,这不好。

您可以将fetchList 调用包装在一个微任务中:

  useEffect(() {
    Future.microtask(() => model.fetchList());
  }, []);

【讨论】:

    【解决方案2】:

    我知道这个问题很老了。但我希望我的回答可以帮助别人。我通过在下一帧中调用函数解决了这个问题

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

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2020-12-28
      • 2021-01-06
      • 2021-05-31
      • 2021-08-24
      • 2020-08-11
      • 2020-06-29
      相关资源
      最近更新 更多