Search code examples
flutterproviderflutter-provider

setState() or markNeedsBuild() called during build. when resetting provider


This code is working fine and resetting provider element but why this error in console. calling this function on init() in stateful class;

 Future getPlotsGraphDataAccordingToCategoryAndDate(context,CategoryId,CategoryName,date) async {
    var getRepresentationProvider =
    Provider.of<RepresentationProvider>(context, listen: false);

    getRepresentationProvider.resetPerticularCategoryDataAccordingDate();

    var response = await http.get(url, headers : {
      'accept': '*/*',
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    });
    final body = jsonDecode(response.body.toString());
    getRepresentationProvider.setCategoryName(CategoryName);
    getRepresentationProvider.setCategoryId(CategoryId);
    getRepresentationProvider.setperticularCategoryDataAccordingDate(

        {
          "TotalInstallmentofplottypeCount":body["data"]["TotalInstallmentofplottypeCount"],
          "paidInstallmentofplottypeCount": body["data"]["paidInstallmentofplottypeCount"],
          "UnpaidInstallmentofplottypeCount":body["data"]["UnpaidInstallmentofplottypeCount"],
          "totalAmountofInstallment": body["data"]["totalAmountofInstallment"],
          "PaidtotalAmountofInstallment": body["data"]["PaidtotalAmountofInstallment"],
          "UnPaidtotalAmountofInstallment":body["data"]["UnPaidtotalAmountofInstallment"]

        }

    ).then((value) {
      print("Here is data Set ${body}");
    });

    return body;
  }

Provider code is below where perticularCategoryDataAccordingDate is set and reset:

   class RepresentationProvider extends ChangeNotifier {

  List perticularCategoryDataAccordingDate = [];


  Future setperticularCategoryDataAccordingDate(data) async {
    perticularCategoryDataAccordingDate.add(data);
    notifyListeners();
    print("object here $perticularCategoryDataAccordingDate");
  }




  Future resetPerticularCategoryDataAccordingDate() async {
    perticularCategoryDataAccordingDate = [];
    notifyListeners();
  }


}

Solution

  • Try this

    void initState() {
        super.initState();
        WidgetsBinding.instance
            .addPostFrameCallback((_) => getPlotsGraphDataAccordingToCategoryAndDate(context,CategoryId,CategoryName,date);
      }