Newbie-want to know how to integrate APIs using provider

`can someone explain me how to integrate apis using provider and model

Provide and Http api call are separate thing.

First understand what is state management and how bloc, provider and other library help in to achieve managing state.

and how to call http api .

1 Like

Yes, http package is used to make API requests, but you can add the method that calls this API inside your provider class. I can give you a simple example of how I do it but it may not be the best. Others do give your thoughts as well. :slight_smile:

newsProvider.dart

class NewsProvider with ChangeNotifier {
  List<NewsModel> _news = []; \\ set initial values
  bool _isLoading = false;

  List<NewsModel> get news {
    return [..._news]; \\ get the current value
  }

  void setNews(news) {
    _news = [...news] 
    notifyListeners(); \\ notifyListeners so that the value is reflected in all consumers
  }

  bool get isLoading {
    return _isLoading;
  }

  set isLoading(value) {
    _isLoading = value;
    notifyListeners();
  }

  void getNews() async {

    if (!isLoading) {
      isLoading = true; \\ to show a progress indicator  in UI

      Map<String, dynamic> responseBody =
          await getRequest("api/v1/news/list"); \\ API call

      if (responseBody['success']) {
        setNews(newsModelFromJson(responseBody['items'])); \\ set the news if successfull
      }
      isLoading = false;
    }
  }
}

request.dart

Future<Map<String, dynamic>> getRequest(url) async {
  final http.Response response =
      await http.get(BASE_URL + url, headers: await getHeaders()).timeout(
          Duration(
            seconds: 4,
          ), onTimeout: () {
    return Future.value(http.Response(json.encode(timeoutResponse()), 400));
  }).catchError((error) {
    return Future.value(http.Response(json.encode(errorResponse()), 500));
  });
  if (response.statusCode < 300 && response.statusCode >= 200) {
    Map<String, dynamic> responseBody = json.decode(response.body);

    responseBody.putIfAbsent("success", () => true);
    return responseBody;
  } else {
    return json.decode((await Future.value(
        http.Response(json.encode(errorResponse()), 500).body)));
  }
}

Future<Map<String, String>> getHeaders() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String token = prefs.getString('jwt_token');
  Map<String, String> headers = {
    "Content-Type": "application/json",
    HttpHeaders.authorizationHeader: "Bearer " + token
  };
  return headers;
}

Finally the UI

  @override
  Widget build(BuildContext context) { \\build method of any class, can be stateless
    return Consumer<NewsProvider>( \\specify the type of provider
      builder: (BuildContext context, newsProvider, _child) {
        return Scaffold(
          body: ListView.builder(
            controller: _scrollController,
            itemCount: newsProvider.news.length,
            itemBuilder: (ctx, i) => i == newsProvider.news.length - 1
                ? newsProvider.isLoading
                    ? Center(child: CircularProgressIndicator()) \\show loader till you get the API response
                    : Container()
                : NewsItem(newsProvider.news[i]), \\any Widget to display data 
          )
        );
      },
    );
  }
1 Like