AWS Amplify Analytics with Flutter
This blog will explore the AWS Amplify Analytics with Flutter. We will also implement a demo program, and learn how to use AWS Amplify Analytics it in your Flutter applications.
If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.
Table of Content
AWS Amplify Libraries:-
The Amplify open-source client libraries are designed to simplify and streamline the interaction between mobile and web developers and their AWS backend resources. These libraries offer easy-to-use interfaces for various categories of AWS cloud operations, making it convenient for developers to integrate and interact with their backend services.
With the Amplify libraries, developers can focus on building their applications without worrying about the intricacies of managing AWS services directly. The libraries provide a set of pre-built functions and APIs that abstract away the complexity of interacting with AWS services, allowing developers to perform common tasks and operations with just a few lines of code.
Whether developers are working with new backends created using the Amplify Command Line Interface (CLI) or existing backend resources, the Amplify libraries can be utilized to simplify the integration and communication process. This flexibility enables developers to seamlessly work with their preferred backend setup and leverage the power of AWS services without needing deep knowledge of AWS-specific APIs or configurations.
Amplify Analytics:-
The Analytics category in Amplify provides functionality to collect analytics data for your application. It offers built-in integration with Amazon Pinpoint and Amazon Kinesis (currently available only in the Amplify JavaScript library).
By using the Analytics category, you can track and gather valuable insights about user behavior, engagement, and usage patterns within your app. This data can be used to make informed decisions, improve user experiences, and optimize your app’s performance.
The Analytics category relies on Amazon Cognito Identity pools to identify and differentiate users within your app. It allows you to collect data from both authenticated and unauthenticated users, providing a comprehensive view of user interactions.
Uses:-
— Capturing User Events One of the primary benefits of Amplify Analytics is its ability to capture user events. You can track various events in your app, such as screen views, button clicks, form submissions, and more. By logging these events, you can understand how users navigate through your app and identify areas for improvement.
The Amplify Flutter library provides a AnalyticsRecordEvent
API that allows you to log custom events with associated attributes and metrics. For example, you can log an event when a user adds a product to their cart and include attributes such as the product ID, name, and price. These events and associated data are then sent to the Amplify Analytics service for analysis.
— User Session Tracking Amplify Analytics also enables you to track user sessions, which provide valuable insights into how users engage with your app over time. A session represents a period of user activity within your app, typically starting when the app is launched and ending when the app is closed or put into the background.
The Amplify Flutter library automatically tracks user sessions and records session-related data, such as the session start time, duration, and the number of events logged during the session. This information can help you understand user engagement patterns and identify trends or anomalies.
— User Demographics and Segmentation Understanding your app’s user demographics is crucial for tailoring your app’s features and content to your target audience. Amplify Analytics allows you to collect user demographic data, including attributes such as age, gender, location, and language preferences.
By leveraging this demographic data, you can segment your user base and gain insights into how different user groups interact with your app. For example, you can analyze the behavior of users from different regions or age groups to identify specific usage patterns and preferences. This information can guide your decision-making process when designing new features or optimizing existing ones.
— Data Visualization and Analysis AWS Amplify Analytics provides a comprehensive set of tools for visualizing and analyzing user behavior data. The Amplify Console, a web-based management console, allows you to view real-time metrics and create custom dashboards to monitor your app’s key performance indicators (KPIs).
Integration with Flutter:-
Integrating AWS Amplify Analytics into a Flutter app is a straightforward process. First, you need to set up an Amplify project and configure the Analytics category. This involves creating an Amplify project, adding the Analytics category, and configuring the necessary settings such as the Amazon Pinpoint project.
Once the setup is complete, you can use the Amplify Flutter library to start tracking user events and sending them to the Amplify Analytics service. The library provides a set of APIs that allow you to log custom events, record user sessions, and track user demographics. These APIs are designed to be simple and intuitive, making it easy to instrument your app with analytics capabilities.
Installation:-
There are a few packages that need to be imported into our Flutter project to implement Amplify Analytics.
Add packages to the dependency block, like below,
dependencies:
amplify_flutter: ^0.6.0
amplify_auth_cognito: ^0.6.0
amplify_authenticator: ^0.2.0
amplify_storage_s3: ^0.6.0
amplify_api: ^0.6.0
Pre-requisites:-
Before starting make sure of these steps.
- Install the latest version of Flutter.
- Create an account on AWS Amplify if you do not have one.
- Create a user and generated a security key.
We need to setup amplify in our project, to install run the following command in your terminal
npm install -g @aws-amplify/cli
Afterward, initialize amplify in the flutter project. To do so follow the below steps:
— To ensure proper installation of the Amplify CLI version, execute the following command:
amplify --version
— To connect to the AWS cloud and initialize Amplify, use the following command:
amplify init
Once you’re done, you will find a file automatically created for configurations of amplify, named ‘amplifyconfiguration. dart’. This will help connect your project to AWS Amplify.
— To initialize Amplify, you need to call the Amplify.configure()
method. Here’s an example of how to initialize Amplify:
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
...
@override
void initState() {
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}
...
}
In the above, the _configureAmplify()
function is called to initialize Amplify. The method uses the Amplify.addPlugin()
method to add the required plugins (such as AmplifyAuthCognito
and AmplifyDataStore
) to Amplify. It then calls Amplify.configure()
with the amplifyconfig
object to provide the necessary configuration.
Code Implementation:-
- main.dart:-
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Authenticator(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true),
home: const MyHomePage(title: 'Flutter Amplify Quickstart'),
builder: Authenticator.builder(),
));
}
@override
void initState() {
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _nameController = TextEditingController();
final _locationController = TextEditingController();
final _languageController = TextEditingController();
UserProfile? _userProfile;
@override
void initState() {
super.initState();
_getUserProfile();
}
void _getUserProfile() async {
final currentUser = await Amplify.Auth.getCurrentUser();
GraphQLRequest<PaginatedResult<UserProfile>> request = GraphQLRequest(
document:
'''query MyQuery { userProfilesByUserId(userId: "${currentUser.userId}") {
items {
name
location
language
id
owner
createdAt
updatedAt
userId
}
}}''',
modelType: const PaginatedModelType(UserProfile.classType),
decodePath: "userProfilesByUserId");
final response = await Amplify.API.query(request: request).response;
if (response.data!.items.isNotEmpty) {
_userProfile = response.data?.items[0];
setState(() {
_nameController.text = _userProfile?.name ?? "";
_locationController.text = _userProfile?.location ?? "";
_languageController.text = _userProfile?.language ?? "";
});
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Image.asset(
"assets/background.jpg",
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
backgroundColor: Colors.transparent,
foregroundColor: Colors.white,
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 30),
child: Padding(
padding: const EdgeInsets.all(30),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Text(
'User Profile',
style: Theme.of(context).textTheme.titleLarge,
)),
const ProfilePicture(),
TextField(
decoration: const InputDecoration(labelText: "Name"),
controller: _nameController,
),
TextField(
decoration:
const InputDecoration(labelText: "Location"),
controller: _locationController,
),
TextField(
decoration: const InputDecoration(
labelText: "Favourite Language"),
controller: _languageController,
)
],
),
))),
floatingActionButton: FloatingActionButton(
onPressed: _updateUserDetails,
tooltip: 'Save Details',
child: const Icon(Icons.save),
),
)
],
);
}
Future<void> _updateUserDetails() async {
final currentUser = await Amplify.Auth.getCurrentUser();
final updatedUserProfile = _userProfile?.copyWith(
name: _nameController.text,
location: _locationController.text,
language: _languageController.text) ??
UserProfile(
userId: currentUser.userId,
name: _nameController.text,
location: _locationController.text,
language: _languageController.text);
final request = _userProfile == null
? ModelMutations.create(updatedUserProfile)
: ModelMutations.update(updatedUserProfile);
final response = await Amplify.API.mutate(request: request).response;
final createdProfile = response.data;
if (createdProfile == null) {
safePrint('errors: ${response.errors}');
}
}
}
You’ll find the entire code file in the GitHub Link section below.
Final Output:-
When we run the application, we ought to get the screen’s output like the underneath screen video.
Conclusion:-
In this article, we have delved into the implementation of AWS Amplify Analytics in our Flutter application. By incorporating this powerful tool, we can effortlessly track user events, enabling us to gain valuable insights into user behavior and app performance.
Now that you have gained an understanding of the process, feel free to customize and experiment with your unique approach. Unleash your creativity and explore the vast potential of AWS Amplify Analytics in optimizing your app’s success.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
GitHub Link:-
🖥️ Github Project —
GitHub – flutter-devs/aws_analytics_demo: AWS Amplify Analytics
AWS Amplify Analytics. Contribute to flutter-devs/aws_analytics_demo development by creating an account on GitHub.github.com
Reference:-
📃 AWS Amplify Docs — https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.