Fluttering On Rails: Part 2 Create Action, Item Params & Flutter HTTP Request
OK welcome back, congrats on making it this far! In this post we are going to enable a create action in our Rails Item Controller. Then we are going to switch over to Flutter were we will be creating our Request class to handle all of our communication with the API.
https://github.com/gardnerapp/Fluttering_on_Rails_Front
https://github.com/gardnerapp/Fluttering_on_Rails_db
Let us begin!
In Rails head over to app/controllers/v1/items and type in
#POST /v1/items
def create
@item = Item.new(item_params)
if @item.save
render json: @item
else
render error: {error: 'Unable to create item' }, status: :bad_request
end
end
This is our create action, when an http POST request is sent to /v1/items with the correct json parameters the action will save the Item (stored in json format) to the database. The :bad_request symbol returns and http status code of 400 in the event that our item does not save. This will come in handy when we need to tell our user (via page routing in the UI) wether their Item was able to be created.
next we have to create our private methods for the items controller, after the create action type:
private def item_params
params.require(:item).permit(:name, :price)
end
The private block establishes private methods which are only available for the controller they are defined in. The item_params method does two things: 1) it keeps our code DRY, without it we would have to continuously type out the parameters for every method and 2) allows us to sanitize our request by only permitting the :name and :price symbols. Without sanitization an attacker could save unwanted information to the database.
Time To Spread Our Wings, Let’s Flutter
Open your flutter repo and create a requests folder, inside this folder create the file crud_services.dart . This file will hold the Dart request class which will hold all of the methods for making requests to our API.
Import the following libraries (we won’t use all of them right now)
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
Next create a CrudServices class with a basUrl & headers fields. These fields will be utilized in each of our http request.
class CrudServices{
String baseUrl = "http://localhost:3000/v1/items"; Map<String, String> headers = {"Content-Type": "application/json; charset=UTF-8" };
}
Obviously if your API is deployed to the web you would substitute localhost:3000 with the URL your app resides at.
Now it’s time to create our create method, inside of CrudServices add:
Future<http.Response> createItem(String name, String price) async{ var body = jsonEncode({"name": name, "price": price}); http.Response response = await http.post(baseUrl, headers: headers, body: body); return response
}
We use a Future http response code as a return value to signal to the user wether our request was successful or not. If we get 200 back we’ll tell the user it worked. If we get a 400 back it did not work.
in the http.post function we pass 1) the url we are sending the request to, 2) the headers which specify that the request is in JSON format with UTF characters and 3) the body of our request which takes the name and price of the item we want to create and serializes them into JSON format so our API can understand them.
We wait for our response with the asynchronous await statement because communication over the web can be a little bumpy sometimes. The await keyword tells the program to pause until the request is fulfilled.
That’s it for this post. Next we will start building the Home and Create pages of our Flutter UI!
Learn Ruby & React FOR FREE Here: https://www.youtube.com/channel/UCfd8A1xfzqk7veapUhe8hLQ
checkout my podcast: https://anchor.fm/coreys-corner