How to get data from server with provider architecture

Viewed 1047

I am new to flutter and recently I watch some videos about state management and provider.

I used statefulwidget and in it's initstate I fetched data. Now is it possible to fetch data in stateless one and manage data in our provider class?

Thanks. Any help is appreciated.

1 Answers

Yes you can fetch data from stateless widget

Example:-

class RecipeProvider with ChangeNotifier {

bool isLoading = false;

void fetchAnyData(BuildContext context) {
    //your data fetching logic 
    isLoading = true;
    ApiManager.downloadRecipeApi().then((recipeList) {
      this.recipes = recipeList;
      isLoading = false;
      notifyListeners();
      print("===Success $recipeList");
    }).catchError((onError) {
      isLoading = false;
      notifyListeners();
      print("===onError $onError");
      Toast.show(onError.errorMsg, context, duration: 2);
    });
  }
}

ProviderFetchWidget.dart

    class ProviderFetchWidget extends StatelessWidget {

      @override
      Widget build(BuildContext context) {

      final _provider = Provider.of<RecipeProvider>(context);
      _provider.fetchAnyData(context);

      return Scaffold(
      body: provider == null || provider.isLoading
          ? Center(child: CircularProgressIndicator())
          : Center(child: Text("data fetching done")),
    );
   }
Related