Feature flags help you conditionally roll out and release features safely. This tutorial shows you how integrate them into your Flutter app using PostHog.
We'll create a basic Flutter app, add PostHog, create a feature flag, and then implement the flag to control content in our app.
1. Create a new Flutter app
Our app will have two screens:
The first screen will have a button which takes you to a second screen.
The second screen will either have a red or green background color, depending on whether our feature flag is enabled or not.
To set this up, first ensure the Flutter extension for VS Code is installed. Then, create a new app by opening the Command Palette in VS Code (Ctrl/Cmd + Shift + P), typing flutter and selecting Flutter: New Project.
Select Empty Application and name your app flutter_feature_flags. Then, replace your code in lib/main.dart with the following:
lib/main.dart
import'package:flutter/material.dart';
import'feature_screen_view.dart';
voidmain(){
runApp(constMyApp());
}
classMyAppextendsStatelessWidget{
constMyApp({super.key});
@override
Widgetbuild(BuildContext context){
returnconstMaterialApp(
title:'Flutter Feature Flags App',
home:MainScreen(),
);
}
}
classMainScreenextendsStatelessWidget{
constMainScreen({super.key});
@override
Widgetbuild(BuildContext context){
returnScaffold(
appBar:AppBar(title:constText('Main Screen')),
body:Center(
child:Column(
mainAxisAlignment:MainAxisAlignment.center,
children:<Widget>[
constText('Hello, world!'),
ElevatedButton(
child:constText('Go to Next Screen'),
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(builder:(context)=>constFeatureScreenView(isFlagEnabled:false)),// We update this later
);
},
),
],
),
),
);
}
}
Lastly, in the lib directory, create a new file for our second screen called feature_screen_view.dart. Add the following code to it:
<meta-dataandroid:name="com.posthog.posthog.POSTHOG_HOST"android:value="https://us.i.posthog.com"/><!-- usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' -->
With PostHog set up, your app is ready for feature flags. To create one, go to the feature flags tab in PostHog and click New feature flag. Enter a flag key (like my-cool-flag), set the release condition to roll out to 100% of users, and press "Save."