如何从回调函数中调用changeNotifier?颤动

问题描述 投票:0回答:2

我从 Flutter 应用程序中的构建函数调用一个函数。 当我从异步回调函数调用

notifyListeners();
时,出现以下异常:

setState() or markNeedsBuild() called during build.

我的提供商:

class TechTaskProvider extends ChangeNotifier {
  ...
  void requestTasks() {
   
    CollectionReference<Map<String, dynamic>> _collection =
        FirebaseFirestore.instance
            .collection('techTasks')
            .doc(_currentTech!.uid)
            .collection('techTasks');

    _collection.get().then((s) {
        _handleResult(s);
        notifyListeners();
    });
}
  

我的触发器小部件:

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

  @override
  State<Trigger> createState() => _TriggerState();
}

class _TriggerState extends State<Trigger> {
  @override
  Widget build(BuildContext context) {
    MyProvider _myProv = Provider.of<MyProvider>(context);
    //
    if (isFirstRun) {
      //Set the first techincian:
      isFirstRun = false;
      // //Trigger Firestore request:
      _myProv.requestTasks();
    }
    return Page();
  }
}
flutter callback flutter-provider
2个回答
0
投票

这样的事情应该可以解决问题:

class _TriggerState extends State<Trigger> {
  @override
  Widget build(BuildContext context) {
    MyProvider _myProv = Provider.of<MyProvider>(context);
    //
    if (isFirstRun) {
      //Set the first techincian:
      isFirstRun = false;
      // //Trigger Firestore request:
      WidgetsBinding.instance!.addPostFrameCallback((_) => _myProv.requestTasks());

    }
    return Page();
  }
}

0
投票

下面是不使用变量的更好解决方案

isFirstRun

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

  @override
  State<Trigger> createState() => _TriggerState();
}

class _TriggerState extends State<Trigger> {
  late final MyProvider _myProv;

  @override
  void initState() {
    super.initState();
    // The below line will be executed JUST AFTER first `build` AND ONLY single time.
    WidgetsBinding.instance.addPostFrameCallback((_) => _myProv.requestTasks());
  }

  @override
  Widget build(BuildContext context) {
    return Page();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.