Flutter On Rails

Flutter On Rails

This tutorial will walk you through how I built this application. Checkout the demo and the repos below base on your own behalf.

Rails Repo => https://github.com/redhaanggara21/Fluttering_on_Rails_db

Flutter Repo=> https://github.com/redhaanggara21/Fluttering_on_Rails_Front

Create a New Flutter and Rails Projects

Start a normal Flutter project and start a Rails project in API mode by using the command:

rails new --api flutter_crud

Generate an Item Model

We could just generate a scaffold and make our lives easy and if thats what you want to do you can run (from the directory holding your rails app).

rails g scaffold Item name:string price:integerrails g model Item name:string price:integer

if your new to Rails the first command generates both a model and a CRUD controller for the Item model. The second command only generates the model itself. In Rails a model is a way of representing data from the database as a ruby object. This is easier then directly dealing with the database itself because we no longer have to write SQL or PG queries by hand.

lets migrate our database:

rails db:migrate

Generate an Item Controller

A controller is a way for users to interact with the application. In rails controller’s are classes and the methods of the class are called actions. Each action is requested via a HTTP request, from there the action does what we program it to do ie. Create,Read Update or Destroy. Rather then having our views shown in HTML format we will have pages in our flutter application act as our views. If your not familiar with MVC architecture read:

To generate a new controller run the command:

rails g controller v1/Items

Usually we don’t prefix controllers with things like v1 but doing so makes it easier to control the API version we are working with, v1 ie. version 1.

head to the app/config/routes.rb file. This file is where we specify the relationship between our application URLs and the actions of our controller. In this file add:

namespace :v1 do
       resources :items
end

using the namespace block with the v1 symbol prefixes all of our items controller actions with /v1. The Resources method makes CRUD urls, and the subsequent actions of the items controller available.All request to the items_controller will follow this format:

base_url/v1/items/action_name

If your application is running locally the base_url will be localhost:3000. To see the new routes, the actions and the keywords they correspond with you can run:

rails routes

That concludes this post, in our next post we will start by creating the Create action in our items controller and begin designing the home and create screen of our flutter UI. Stay tuned !