Search code examples
flutterdartflutter-dependenciesproviderflutter-change-notifier

Unable to create getter in Changenotifier class. error when using Provider in Flutter


hello i am new with provider. i wrote steps here where i have problem. 1- i called api after that i have data in my Model class. 2- then in ChangeNotifer class i want to make getter of list which is in Model class object. i am unable to add model class response data to this getter variable.

class CartProductNotifier with ChangeNotifier{

final _webServices = WebServices();
GetProductDetailsModel _getProductDetailsModel;
List<Vd> _vdList = [];

callApi(String handle) {
    return _webServices.getProductDetails(handle).then((value) {
      _getProductDetailsModel = value;
      _vdList = value.data.product.vd; // after api call done data is in _vdList
      return value;
    });
  }

}

now i am creating getter

List<Vd> get vdata {
   return _vdList;
 }

but when i called this getter from my ProductDetailsScreen class i am getting blank array or null.

 Consumer<CartProductListNotifier>(
                  builder: (context, value, child) {
                    return Text(
                       value.vdata[index].quantitySelectedByUser.toString(),  //data is not coming here
                    style: TextStyle(
                    fontSize: kFontSize16, fontWeight: kMediumFontWeight, color: Colors.black),
                    );
                  },
                ),

now i am unable to update value in Text widget which is in Consumer notifier.

this is my main.dart

MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => CartProductListNotifier(),
        ),
      ],
      child: MaterialApp(
        title: 'Application',
        debugShowCheckedModeBanner: false,

please solve this issue or told me another good way to Call Api with Model class with Provider. Thanks in Advance.


Solution

  • call setData function after calling API is solved my problem now i am getting result in _vdList.

    example

    setData(GetProductDetailsModel _productModel) {
       _getProductDetailsModel = _productModel;
       _vdList = _productModel.data.product.vd;
       _voList = _productModel.data.product.vo;
       notifyListeners();
     }