Making FlutterAPI Calls Easy

I read somewhere that programmers begin to lose concentration and productivity when their files exceed ~120 lines. Dart is a statically typed language that tends to eat up a lot of space, making API calls to your backend can become a bit of a hassle if you don’t organize yourself properly.

The first thing I like to do is create a BaseAPI class to store all of the URLs my app will be requesting:

BaseAPI{

static var rootUrl = "https://localhost:3000/"

var usersPath = rootUrl + "users"

// More Urls

}

By defining root as a static var we do two things 1) We can append the other directories of our API to rootURL in order to keep our code DRY and 2) When we go live on the server we only have to switch one string from localhost:3000 to “IPofMyServer”. DRY code is quicker to build and refactor.

Personally I like to break my API request up into specific parts for example I’ll have a whole class dedicated to actions a user will be taking and I’ll have a whole other class dedicated to authentication actions:

// A class for handling users actions

class UserActions extends BaseAPI{

// Various API Calls

}

// Login, Logout, etc.

class AuthenticationActions extends BaseAPI{

// Appropriate API Request here

}

In actual projects I’ll create an API folder and inside of this folder there will be files holding each of the individual separate classes for the specific type of API request.

How do we access the URLs defined in our BaseAPI Class? Calling super inside of our child classes allows us to access the instance variables of our parent class:

class UserActions extends BaseAPI{

Future<http.Response> getUsers() async {

http.Response response = await http.get(super.usersPath, body: body, headers: headers)

}

}

In conclusion, compartmentalize your code because it’ll help you be more productive and save you a lot of stress. Create a mother API class to store all of the URLs, headers and other redundant data that is near universal to all of your API calls. Then for define a separate class for each functional type of API request you are making.