Building a Telegram Mini App with Flutter
What is Telegram Mini App?
Telegram Mini Apps provide a seamless way to integrate external apps directly into the Telegram environment. Users can interact with these apps within the chat interface, making for a more fluid user experience.
Before starting, make sure you’ve already set up a Flutter project using GetX state management. GetX is a popular and lightweight state management solution for Flutter that simplifies reactive programming, dependency injection, and routing. If you’re new to GetX, you can refer to the official documentation to get started.
Here’s a quick overview of the Telegram Web App setup process:
- Telegram Web App Object: The
window.Telegram.WebApp
object gives access to various properties and methods to control the behavior of your mini-app. - Initialization: When a mini-app is loaded, Telegram automatically initializes the
Telegram.WebApp.init()
function. This handles app setup, such as the title and back button behavior. - Accessing User Information: You can access user details like
user_id
,first_name
, andlast_name
throughTelegram.WebApp.initDataUnsafe
. - Sending Data Back to Telegram: After interacting with the mini-app, you can send data back to Telegram using
Telegram.WebApp.sendData("your_data_here")
. This method allows you to pass information back to the bot. - Customizing Button Controls: Use
Telegram.WebApp.MainButton
to control the appearance of buttons within the app interface, allowing further customization.
Now, let’s dive into how to integrate this with Flutter.
Step 1: Add JavaScript Interop Support in Flutter
To interact with JavaScript functions from your Dart code in Flutter, you’ll need to use the dart:js
library.
- Open your
pubspec.yaml
file and add the following dependency:
dependencies:
js: ^0.6.3
Step 2: Add JavaScript Code to Your HTML
Next, you need to insert the Telegram WebApp initialization JavaScript code into the HTML file of your Flutter web project. This can be found in the web/index.html
file, inside the <head>
tag.
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script>
function initTelegramWebApp() {
if (window.Telegram) {
Telegram.WebApp.ready();
return Telegram.WebApp.initDataUnsafe;
}
return null;
}
function sendTelegramData(data) {
if (window.Telegram) {
Telegram.WebApp.sendData(data);
}
}
function setMainButton(text, isVisible) {
if (window.Telegram) {
Telegram.WebApp.MainButton.setText(text);
if (isVisible) {
Telegram.WebApp.MainButton.show();
} else {
Telegram.WebApp.MainButton.hide();
}
}
}
</script>
Step 3: Create Dart Functions to Call JavaScript
In your Flutter app, use Dart’s interop library to call JavaScript functions. To manage this, create a TelegramController
class that will interact with the JavaScript functions.
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'dart:js' as js;
class TelegramController extends GetxController {
Map<String, dynamic>? telegramData;
@override
void onInit() {
super.onInit();
getTelegramData();
}
void getTelegramData() {
telegramData = initTelegramWebApp();
if (telegramData != null) {
debugPrint('Telegram Data: $telegramData');
} else {
debugPrint('Telegram data is null. This app is opened outside telegram');
}
update();
}
// Function to initialize the Telegram WebApp
static Map<String, dynamic>? initTelegramWebApp() {
final result = js.context.callMethod('initTelegramWebApp');
debugPrint("result: $result");
if (result != null) {
// Convert JsObject to JSON string and then parse it to a Map
String jsonString = js.context['JSON'].callMethod('stringify', [result]);
return jsonDecode(jsonString);
}
return null;
}
// Function to send data back to Telegram
static void sendTelegramData(String data) {
js.context.callMethod('sendTelegramData', [data]);
}
// Function to control the MainButton in Telegram
static void setMainButton(String text, bool isVisible) {
js.context.callMethod('setMainButton', [text, isVisible]);
}
}
Step 4: Use the Telegram API in Your Flutter Widget
Now, you can use the TelegramController
class to interact with the Telegram API within your Flutter widget. Here’s an example of how you can display user information in your app:
GetBuilder<TelegramController>(builder: (telegramController) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(
children: <Widget>[
const CircleAvatar(
backgroundImage: AssetImage('assets/captain.jpg'),
radius: 30.0,
),
const SizedBox(height: 8.0),
Text(
'Capt. ' + (telegramController.telegramData?['user']?['username'] ?? 'Unknown'),
style: const TextStyle(fontSize: 16),
),
],
),
(telegramController.telegramData != null && telegramController.telegramData!['user'] != null)
? Column(
children: [
Text(
telegramController.telegramData?['user']?['first_name'] ?? 'Unknown',
style: const TextStyle(fontSize: 16),
),
Text(
telegramController.telegramData?['user']?['id'].toString() ?? 'Unknown',
style: const TextStyle(fontSize: 16),
),
],
)
: Container(),
],
);
})
This code displays a user’s Telegram username, first name, and user ID within the app interface.
Step 5: Deploying Flutter Web to Vercel
After developing your Flutter Web app, it’s time to deploy it to Vercel. Follow these steps:
- Push Your Code to Git: Make sure your code is committed and pushed to a Git repository.
- Deploy to Vercel
Configure your Vercel project with the following settings:
- Build Command:
flutter/bin/flutter build web --release
- Output Directory:
build/web
- Install Command:
if cd flutter; then git pull && cd .. ; else git clone --branch flutter-3.21-candidate.12 https://github.com/flutter/flutter.git; fi && ls && flutter/bin/flutter doctor && flutter/bin/flutter clean && flutter/bin/flutter config --enable-web
You can check for available Flutter versions here.
Once the deployment is complete, your app will be accessible. Here’s an example of a deployed app:
https://flutter-telegram-miniapp.vercel.app/
Step 6: Create a Telegram Bot
Now, you need to create a Telegram bot to link with your mini-app. You can create it from https://t.me/BotFather
Save your bot token for future backend access. Let’s continue with creating new app on telegram
Once the bot is set up, you can easily test the app by clicking on the web app. You should be able to retrieve the Telegram username, first name, and user ID.
With that, you’ve successfully built and deployed a Flutter-based Telegram Web App on Vercel. Integrating your service into Telegram opens up exciting opportunities to reach users more effectively without leaving their messaging environment.
You can check the full source code in here
Here are some examples of successful mini apps that have many users that you can use as a reference.
References:
Telegram WebApps Documentation