1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-05-31 01:16:01 +02:00

docs: Added Flutter and Next.js Tutorials

This commit is contained in:
Pranshu Khanna 2023-10-19 17:40:00 +02:00
parent f22c15e5a1
commit b5dd8f132f
17 changed files with 6416 additions and 94 deletions

View File

@ -105,6 +105,7 @@
"db-migrate-shared": "1.2.0",
"deep-object-diff": "^1.1.9",
"deepmerge": "^4.2.2",
"docusaurus": "^1.14.7",
"errorhandler": "^1.5.1",
"express": "^4.18.2",
"express-rate-limit": "^6.6.0",

View File

@ -0,0 +1,412 @@
---
title: A/B Testing in Flutter using Unleash and Mixpanel
---
:::note
This article is a contribution by **[Ayush Bherwani](https://www.linkedin.com/in/ayushbherwani/)** as a part of the **[Community Content Program](https://github.com/unleash/community-content)**. You can also suggest a topic by [opening an issue](https://github.com/Unleash/community-content/issues), or [Write for Unleash](https://www.getunleash.io/blog/get-published-through-unleashs-community-content-program) as a part of the Community Content Program.
:::
After successfully integrating the first feature flag in the Unsplash sample app, lets talk about how you can use Unleash to perform experimentation, also known as A/B testing, in Flutter to ship features more confidently.
For this article, well integrate feature flags for A/B testing to experiment with “like image” feature user experience. As an overview, the app is quite simple, with two screens displaying images and image details respectively. The behavior of the “image details” feature is controlled through an Unleash instance. You can check out the previous article, “[How to set up feature flags in Flutter](https://www.getunleash.io/blog/from-the-community-how-to-set-up-feature-flags-in-flutter)” for an overview of the code structure and implementation. For those who want to skip straight to the code, you can find it on [GitHub](https://github.com/AyushBherwani1998/unsplash_sample/).
Heres a screenshot of the application:
![Unsplash App built on Flutter](/img/unsplash-demo-flutter.png)
## Setup variants in Unleash
In your Unleash instance, create a new feature flag called `likeOptionExperiment`. Choose the toggle type called `Experiment` and enable the [impression data](https://docs.getunleash.io/reference/impression-data). By default, the flag will be set to false.
![Set Up Variant in Unleash](/img/variant-setup-1.png)
Now that you have created your feature toggle, lets create two new [variants](https://docs.getunleash.io/reference/feature-toggle-variants) “gridTile'' and “imageDetails” respectively. These variants will help you position your “like image” button.
![Succesfully setting up variant in Unleash](/img/setup-variant-2.png)
Below is a screenshot of experimentation in action based on the `likeOptionExperiment` flag and corresponding variants.
![Unsplash App built on Flutter](/img/unsplash-flutter-demo-screenshot-2.png)
## Setup Mixpanel
For analytics and metrics, well use [Mixpanel](https://mixpanel.com/) to track user behavior and usage patterns. We have chosen Mixpanel because it offers a user-friendly setup and in-depth user analytics and segmentation. Given that the project follows clean architecture and Test-Driven Development (TDD) principles, youll want to create an abstract layer to interact with the Mixpanel.
Whenever a user opens the app, we track `like-variant` if `likeOptionExperiment` is enabled to tag them with their assigned variant (gridTile or imageDetails). The stored variant in Mixpanel can be used later to analyze how each variant impacts user behavior to like an image.
Whenever a user interacts with the `LikeButton`, we track `trackLikeEventForExperimentation`, along with their assigned variants. By correlating the `trackLikeEventForExperimentation` with the `like-variant`, you can effectively measure the impact of a variant on user behavior and make data-driven decisions. To learn how to correlate and generate reports, see the [Mixpanel docs](https://docs.mixpanel.com/docs/analysis/reports).
```
abstract class MixpanelConfig {
/// ...
/// Helps you get the metrics of experimentation to analysis
/// the different position of the share image button.
void trackLikeEventForExperimentation({
required LikeButtonPosition likeButtonPosition,
required String photoId,
});
/// Help you get the variant based on which we can create funnel
/// for analytics.
void trackLikeVariant(LikeButtonPosition likeButtonPosition);
}
class MixpanelConfigImpl implements MixpanelConfig {
final TargetPlatformExtended targetPlatformExtended;
MixpanelConfigImpl(this.targetPlatformExtended);
Mixpanel get mixpanel {
return ServiceLocator.getIt<Mixpanel>();
}
/// ...
@override
void trackLikeEventForExperimentation({
required LikeButtonPosition likeButtonPosition,
required String photoId,
}) {
if (targetPlatformExtended.isMobile) {
mixpanel.track('like-experimentation', properties: {
"variant": describeEnum(likeButtonPosition),
"photoId": photoId,
});
}
}
@override
void trackLikeVariant(LikeButtonPosition likeButtonPosition) {
if (targetPlatformExtended.isMobile) {
mixpanel.track('like-variant', properties: {
"variant": describeEnum(likeButtonPosition),
});
}
}
}
```
Once you have your configuration in place, the next step is to create `MixPanel` and `MixpanelConfig` and add it to your service locator class. Make sure that you have a Mixpanel[ API key](https://docs.mixpanel.com/docs/tracking/how-tos/api-credentials).
```
class ServiceLocator {
ServiceLocator._();
static GetIt get getIt => GetIt.instance;
static Future<void> initialize() async {
/// ...
final unleash = UnleashClient(
url: Uri.parse('http://127.0.0.1:4242/api/frontend'),
clientKey: dotenv.env["UNLEASH_API_KEY"] as String,
appName: 'unplash_demo',
);
await unleash.start();
getIt.registerLazySingleton(() => unleash);
getIt.registerLazySingleton<UnleashConfig>(
() => UnleashConfigImpl(getIt()),
);
getIt.registerLazySingleton<WebPlatformResolver>(
() => WebPlatformResolverImpl(),
);
final TargetPlatformExtended targetPlatformExtended =
TargetPlatformExtendedImpl(getIt());
getIt.registerLazySingleton<TargetPlatformExtended>(
() => targetPlatformExtended,
);
if (targetPlatformExtended.isMobile) {
final mixPanel = await Mixpanel.init(
dotenv.env["MIXPANEL_KEY"] as String,
trackAutomaticEvents: false,
);
getIt.registerLazySingleton(() => mixPanel);
}
getIt.registerLazySingleton<MixpanelConfig>(
() => MixpanelConfigImpl(getIt()),
);
/// ...
}
}
```
## Integration in Flutter
Lets dive into how you can use these variants in your Flutter application.
Youll have to modify `UnleashConfig` which helps you test the Unleash functionalities in isolation from the rest of the app.
```
const String isImageDetailsEnabledToggleKey = "isImageDetailsEnabled";
const String likeOptionExperimentKey = "likeOptionExperiment";
/// Helps determine the position of like button
/// [gridTile] will be used to position like image button
/// on [ImageTile].
/// [imageDetails] will be used to position like image button
/// inside the [ImageDetails] page.
enum LikeButtonPosition { gridTile, imageDetails }
abstract class UnleashConfig {
/// ...
bool get isLikeOptionExperimentEnabled;
LikeButtonPosition get likeButtonPosition;
}
class UnleashConfigImpl extends UnleashConfig {
final UnleashClient unleash;
UnleashConfigImpl(this.unleash);
/// ...
@override
bool get isLikeOptionExperimentEnabled =>
unleash.isEnabled(likeOptionExperimentKey);
@override
LikeButtonPosition get likeButtonPosition {
final variant = unleash.getVariant(likeOptionExperimentKey);
return LikeButtonPosition.values.byName(variant.name);
}
}
```
After updating `UnleashConfig` you may want to create a `_trackLikeExperimentationVariant` method which you can call in `initState` of “HomePage” to get the variant details.
```
void _trackLikeExperimentationVariant() {
final unleashConfig = ServiceLocator.getIt<UnleashConfig>();
final mixpanelConfig = ServiceLocator.getIt<MixpanelConfig>();
if (unleashConfig.isLikeOptionExperimentEnabled) {
mixpanelConfig.trackLikeVariant(unleashConfig.likeButtonPosition);
}
}
```
Youll create a new widget “LikeButton'' which can be utilized for both variants. Make sure to use `MixpanelConfig` to track user engagement for analytics purposes.
```
class LikeButton extends StatelessWidget {
final ValueNotifier<bool> isLikedNotifier;
/// Used to track the variant option for the mixpanel event.
final LikeButtonPosition likeButtonPosition;
final String photoId;
const LikeButton({
super.key,
required this.isLikedNotifier,
required this.likeButtonPosition,
required this.photoId,
});
/// Event fired to track the user engagement on liking an image
void _fireMixpanelEvent() {
final mixpanelConfig = ServiceLocator.getIt<MixpanelConfig>();
mixpanelConfig.trackLikeEventForExperimentation(
likeButtonPosition: likeButtonPosition,
photoId: photoId,
);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<bool>(
valueListenable: isLikedNotifier,
builder: (context, isLiked, child) {
return IconButton(
padding: EdgeInsets.zero,
visualDensity: VisualDensity.compact,
iconSize: 20,
isSelected: isLiked,
splashColor: Colors.red,
onPressed: () {
isLikedNotifier.value = !isLikedNotifier.value;
_fireMixpanelEvent();
},
selectedIcon: const Icon(
CupertinoIcons.heart_fill,
color: Colors.redAccent,
),
icon: const Icon(CupertinoIcons.heart),
);
},
);
}
}
```
Once you have created `LikeButton`, the next step is to use the `LikeButtonPosition` to add the button in the `ImageTile` widget, and `ImageDetails` page.
For `ImageTile` make sure the button is only visible if `isLikeOptionExperiment` is enabled and `LikeButtonPosition` is `gridTile`.
```
class ImageTile extends StatelessWidget {
final UnsplashImage image;
final UnleashConfig unleashConfig;
const ImageTile({
super.key,
required this.image,
required this.unleashConfig,
});
bool get isFooterEnabled {
return unleashConfig.isLikeOptionExperimentEnabled &&
unleashConfig.likeButtonPosition == LikeButtonPosition.gridTile;
}
Widget tileGap() => const SizedBox(height: 4);
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
imageUrl: image.url,
cacheManager: ServiceLocator.getIt<DefaultCacheManager>(),
imageBuilder: (context, provider) {
return Column(
children: [
/// Some more widgets
if (isFooterEnabled) ...[
ImageTileFooter(image: image),
],
],
);
},
);
}
}
```
For `ImageDetailsPage` make sure the button is only visible if `isLikeOptionExperiment` is enabled and `LikeButtonPosition` is `imageDetails`.
```
@RoutePage()
class ImageDetailsPage extends StatefulWidget {
final String id;
const ImageDetailsPage({
super.key,
required this.id,
});
@override
State<ImageDetailsPage> createState() => _ImageDetailsPageState();
}
class _ImageDetailsPageState extends State<ImageDetailsPage> {
/// ...
late final MixpanelConfig mixPanelConfig;
late final ValueNotifier<bool> isLikedNotifier;
late final UnleashConfig unleashConfig;
@override
void initState() {
super.initState();
/// ...
mixPanelConfig = ServiceLocator.getIt<MixpanelConfig>();
isLikedNotifier = ValueNotifier<bool>(false);
unleashConfig = ServiceLocator.getIt<UnleashConfig>();
/// ...
_fetchImageDetails();
}
/// ...
void _fetchImageDetails() {
bloc.add(FetchImageDetailsEvent(widget.id));
}
bool get isLikeButtonVisible {
return unleashConfig.isLikeOptionExperimentEnabled &&
unleashConfig.likeButtonPosition == LikeButtonPosition.imageDetails;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(
CupertinoIcons.xmark,
),
),
actions: [
if (isLikeButtonVisible) ...[
LikeButton(
isLikedNotifier: isLikedNotifier,
photoId: widget.id,
likeButtonPosition: LikeButtonPosition.imageDetails,
),
]
],
),
body: /// Body widget;
}
}
```
Now that you have your pieces clubbed, you can toggle the `likeOptionExperiment` flag to enable the experimentation of the “like image” feature in the application.
Voila! Your experimentation is enabled for your feature. Youve also ensured that users can access the “like image” feature depending on the state of the flag and variant.
## Analytics
Once your experimentation is up and running, you can visit the Mixpanel dashboard to create a [funnel](https://docs.mixpanel.com/docs/analysis/reports/funnels) and get insights on the user engagement and conversion rate for different variants.
Below is a funnel screenshot for “like image” experimentation:
![Mixpanel Analytics for A/B Testing in Unleash for the Flutter Demo](/img/mixpanel-flutter-screenshot-1.png)
## Conclusion
A/B testing is a low-risk, high-returns approach that can help you make data-driven decisions for your feature releases to increase user engagement, minimize the risk, and increase conversion rates. As a developer, it helps you be confident in your releases by addressing the issues users face and reducing the bounce rates during experimentation with the help of data.
Some of the best practices for experimentation include:
* You should be open to the results and avoid any hypotheses.
* You should define the metrics for the success of the experimentation before you run the tests. Keep your success metrics simple and narrowed for better results.
* Select a group of adequate size for the test to yield definitive results.
* You should avoid running multiple tests simultaneously, as it may not give reasonable outcomes.
Thats it for today. I hope you found this helpful. Want to dive deep into the code used for this article? Its all on [GitHub](https://github.com/AyushBherwani1998/unsplash_sample/).

View File

@ -0,0 +1,185 @@
---
title: How to Implement Feature Flags in Next.js using Unleash
---
:::note
This article is a contribution by **[Kafilat Adeleke](https://www.linkedin.com/in/kafilat-adeleke-650332222/)** as a part of the **[Community Content Program](https://github.com/unleash/community-content)**. You can also suggest a topic by [opening an issue](https://github.com/Unleash/community-content/issues), or [Write for Unleash](https://www.getunleash.io/blog/get-published-through-unleashs-community-content-program) as a part of the Community Content Program.
:::
Imagine turning on and off features in your web application without redeploying your code. Sounds too good to be true? It's possible with feature flags and Next.js, a powerful framework for building fast and scalable web applications using React.
Feature flags are a powerful technique that allows you to toggle features on and off dynamically without redeploying your code. This can help you to deliver faster and safer web applications, as you can test new features in production, perform gradual rollouts, and revert changes quickly if something goes wrong.
Next.js provides features such as:
- Server-side rendering
- Static site generation
- Code splitting
- Dynamic routing
- TypeScript support
- CSS modules support
- And many more
With Next.js, you can create hybrid applications that can use both static and dynamic pages. Static pages are pre-rendered at build time and served from a CDN, which makes them fast and secure. Dynamic pages are rendered on-demand by a Node.js server, which allows you to use data from any source and handle user interactions. You can also use incremental static regeneration to update static pages without rebuilding your entire application.
However, one of the challenges of using Next.js is that it requires you to rebuild your application every time you want to change something in your code. This can be time-consuming and risky, especially if you want to test new features in production or perform gradual rollouts. Therefore, you need a way to toggle features on and off dynamically without redeploying your code. This is where feature flags come in.
Unleash is an open-source, easy-to-use feature management platform that supports Next.js and other frameworks. With Unleash, you can create and manage feature flags from a user-friendly dashboard and use them in your code with a simple API. Unleash also provides advanced features such as segmentation, strategies, and integrations.
In this tutorial, you will learn how to use feature flags in a Next.js application that displays random activities to users using Unleash. We will use the `@unleash/nextjs` package, which provides easy integration of Unleash feature flags in a Next.js application.
Note: If you only need a very simple setup for feature flags in your Next.js application, like toggling a feature on and off for all users, use the [Vercel Edge Config](https://vercel.com/docs/storage/edge-config/get-started). You can avoid making requests to the Unleash API from your application and instead use the edge config to inject the feature flag values into your pages.
![Next.js Feature Flag Architecture Diagram](/img/nextjs-feature-flag-architecture-diagram-blog.png)
## Setup Unleash
Before you proceed, ensure you have an Unleash instance running. Run the following commands in the terminal:
```
wget getunleash.io/docker-compose.yml
docker-compose up -d
```
This will start Unleash in the background. Once Unleash is running, you can access it at http://localhost:4242.
```
Username: admin
Password: unleash4all
```
## Create a New Feature
Create a new feature flag in your Unleash instance named "activity".
![Create a new feature flag in Unleash](/img/create-new-flag-nextjs.png)
## Integrating Unleash in Nextjs
To get started with Next.js and Unleash, you need to create a Next.js project and add the `@unleash/nextjs` package as a dependency.
You can run the following commands in your terminal to do this:
```
npx create-next-app activity-app
cd activity-app
npm install @unleash/nextjs
```
To make feature flags available to our Next.js application, we will wrap it with the FlagProvider component from the @unleash/nextjs package. This component will initialize the Unleash SDK and provide access to feature flags throughout our application. We will do this by adding it to our `pages/_app.tsx` file.
```
import type { AppProps } from "next/app"
import { FlagProvider } from "@unleash/nextjs/client"
export default function App({ Component, pageProps }: AppProps) {
return (
<FlagProvider>
<Component {...pageProps} />
</FlagProvider>
)
}
```
Next, we will use the Bored API to retrieve a random activity and then use the `useFlag` feature to determine whether the activity is displayed or not.
```
import { useEffect, useState } from "react"
import { useFlag } from "@unleash/nextjs/client"
const Activity = () => {
const [activityData, setActivityData] = useState({})
const showActivity = useFlag("activity")
useEffect(() => {
const fetchActivity = async () => {
try {
const response = await fetch("https://www.boredapi.com/api/activity/")
const data = await response.json()
setActivityData(data)
} catch (error) {
console.error("Error fetching activity:", error)
}
}
if (showActivity) {
fetchActivity()
}
}, [showActivity])
return (
<div className="bg-gray-100 min-h-screen flex items-center justify-center">
<div className="bg-white p-8 rounded shadow-lg">
<h1 className="text-3xl font-bold mb-4">
Here is an activity for you!
</h1>
{showActivity ? (
<>
<p className="mb-2">Activity: {activityData.activity}</p>
<p className="mb-2">Participants: {activityData.participants}</p>
<p>Price: ${activityData.price}</p>
</>
) : (
<p>Activity not available</p>
)}
</div>
</div>
)
}
export default Activity
```
Our feature flag can now be used to control whether or not activity is displayed. If we toggle on the gradual roll out:
![Gradual Rollout](/img/gradual-rollout-nextjs.png)
The activity is displayed:
![Activity Successful](/img/activity-success-nextjs.png)
If we toggle it off:
![Toggle Off](/img/gradual-rollout-nextjs-1.png)
No activity is displayed:
![Activity Successful](/img/activity-success-nextjs-1.png)
To configure access to Unleash beyond localhost development, follow these steps:
- Self-host Unleash or run an instance on [Unleash Cloud](https://www.getunleash.io/pricing).
- Get an API key from the Unleash dashboard.
- Store the API key in your Vercel Project Environment Variable, which secures it and makes it accessible in your code.
## Conclusion
Feature flags are a powerful tool for managing features in web applications. This tutorial showed us how to use feature flags with Next.js and Unleash. We have seen how to create and manage feature flags in the Unleash dashboard, and how to use them in our Next.js code with the @unleash/nextjs library. We have also seen how to test our feature flags by toggling them on and off in the Unleash dashboard.
Unleash is a powerful and easy-to-use feature management platform that can help you deliver faster and safer web applications with Next.js and other frameworks. If you are not already using feature flags in your Next.js applications, I encourage you to try Unleash and see how it can improve your development workflow.

View File

@ -88,6 +88,20 @@ module.exports = {
'topics/feature-flag-migration/onbording-users-to-feature-flag-service',
],
},
{
type: 'category',
link: {
type: 'generated-index',
title: 'Feature Flag Tutorials',
description: 'Tutorials to implement feature flags with your framework.',
slug: 'topics/feature-flags/tutorials',
},
label: 'Feature Flag Tutorials',
items: [
'topics/feature-flags/tutorials/flutter/a-b-testing',
'topics/feature-flags/tutorials/nextjs/implementing-feature-flags'
],
},
'topics/data-collection',
'topics/managing-constraints',
'topics/proxy-hosting',
@ -442,4 +456,4 @@ module.exports = {
],
},
],
};
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 257 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 277 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

5896
yarn.lock

File diff suppressed because it is too large Load Diff