Welcome to the Finch Controllers Guide! This guide will walk you through the steps to create and use controllers in your Finch application. Whether you're a seasoned developer or just starting, Finch offers a robust set of tools to simplify server-side web app development.

What is a Controller?

A controller in Finch is a class that handles HTTP requests. It is responsible for processing the request and generating a response. Controllers are used to organize related request handling logic and can be associated with routes to process incoming HTTP requests.

Creating a Controller

To create a controller, you need to extend the Controller class. Here is an example of how to create a simple controller:

import 'package:finch/finch_route.dart';

class MyController extends Controller {
  MyController();

  @override
  Future<String> index() async {
    return rq.renderString(text: 'Hello World');
  }
}

In this example, we have created a controller called MyController that extends the Controller class. We have also overridden the index method to handle the request and generate a response. The index method is called when a request is made to the route associated with this controller.

Using a Controller

To use a controller, you need to associate it with a route. You can do this by setting the controller property of the FinchRoute class. Here is an example of how to use the MyController we created earlier:

FinchRoute(
  path: '/',
  controller: MyController(),
);

In this example, we have created a route that matches the root path (/) and associated it with the MyController we created earlier. When a request is made to the root path, the index method of the MyController will be called to handle the request and generate a response.

Note:

index function is default function for controller, you can use any name for your function and use it in route definition. for example:

class MyController extends Controller {
  MyController();

  Future<String> myFunction() async {
    return rq.renderString(text: 'Hello World');
  }
}
FinchRoute(
  path: '/',
  controller: MyController(),
  index: MyController().myFunction,
);