Phanindra
Phanindra

Reputation: 1378

Flutter http API calls

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

Upvotes: 2

Views: 362

Answers (3)

Kunj Bhuva
Kunj Bhuva

Reputation: 11

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;
    });   } }

Upvotes: 0

Sparko Sol
Sparko Sol

Reputation: 717

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.

Upvotes: 1

OSID ALSAGHIR
OSID ALSAGHIR

Reputation: 55

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

Upvotes: 0

Related Questions