skip to Main Content

How can I setup a framework for API calling in flutter ?

Instead of just creating a api call function need to create a framework that can be used for multiple future projects

3

Answers


  1. If you are using Dio or any other libraries then the best way is to make a Dio helper class where you can change only the BASE_URL and will be globally used in all other classes after step by step you can add the not changeable things there.

    I hope it helps

    Login or Signup to reply.
  2. You can make a separate project for API calls and models, this project will include the model classes and services for API calls. For API calls you can use retrofit or dio, whatever you want to use. This project will not include the UI, make the project by following command.

    flutter create --template=package api_framework
    

    Now you can include this framework project in many projects you want. Just add the path of this project in pubspec.yaml as following

    dependencies:
      flutter:
        sdk: flutter
    
      api_fremework:
        path: ./api_framework
    

    Now you will be able to call the API functions.

    I hope it helps.

    Login or Signup to reply.
  3. you can try this.

    import 'dart:convert';
    
    import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart';
    
    class callapi extends StatefulWidget {   const callapi({Key? key}) : super(key: key);
    
      @override   State<callapi> createState() => _callapiState(); }
    
    class _callapiState extends State<callapi> {
    
      List<dynamic> data = [];
    
      final uri = "https://jsonplaceholder.typicode.com/posts";
    
      void postdata()async{    final responce = await post(Uri.parse(uri),body:{
          "title": "Anything",
          "body": "Post body",
          "userid": "1",
        });    print(responce.body);
    
      } @override   void initState() {
        // TODO: implement initState
        super.initState();
        apidata();   }   @override   Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: ElevatedButton(onPressed: postdata, child: Text('send data'),),
          )
        );   }   void apidata()async{
        final responce = await get(Uri.parse(uri));
        final jsondata = jsonDecode(responce.body) as List;
        setState(() {
          data = jsondata;
        });   } }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search