Creating a function
Create serverless functions with Celest to connect different parts of your backend, and run custom business logic entirely in the cloud. You define cloud functions as regular Dart functions and Celest will automatically configure the HTTP endpoints, manage the serialization of Dart types to and from JSON and, when you're ready, deploy your functions to the cloud.
Writing Celest Functions
To write your first serverless cloud function, navigate to the my_celest_app/celest/lib/src/functions/
folder and create a file named <api_name>.dart
. You can create as many APIs as you want in this directory.
Each file groups and organizes multiple Celest Functions of similar functionality into a namespace.
Celest Functions are defined as top-level functions as shown below.
Only functions annotated with @cloud
are exposed as cloud functions. This prevents accidental deployment of functions and allows you to have shared logic and helper functions that are not exposed as cloud functions.
@cloud
Future<String> sayHello(String name) async {
return 'Hello, $name';
}
@cloud
Future<String> sayGoodbye(String name) async {
return 'Goodbye, $name';
}
That's all you need to define your API! Now, you can connect your Flutter app to your cloud functions by using the Celest client as shown in the following example. Replace the contents of the main.dart
file in your Flutter app to the following code-snippet.
import 'package:flutter/material.dart';
// Import the generated Celest client
import 'package:celest_backend/client.dart';
void main() {
// Initialize Celest at the start of your app
celest.init(environment: CelestEnvironment.local);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Homepage'),
),
body: Center(
child: FutureBuilder(
// Call your function using the Celest client
future: celest.functions.greeting.sayHello('Celest'),
builder: (_, snapshot) => switch (snapshot) {
AsyncSnapshot(:final data?) => Text(data),
AsyncSnapshot(:final error?) =>
Text('${error.runtimeType}: $error'),
_ => const CircularProgressIndicator(),
},
),
),
),
);
}
}
Next steps
You now know how to create Celest Functions and connect them to your Flutter app. We have other guides to help explain how to use features such as logging, using custom data types, and managing environment variables.