Links

Setup & Authentication

With Amity UIKit 2.3, we have introduced a new way to Authentication process. Just follow the guide below.

Adding required permissions

Your app may require the following permissions to work properly;
  1. 1.
    Camera access
  2. 2.
    Microphone access
  3. 3.
    Photo library usage access
Before submitting your application to the store, please make sure the following permissions are already granted. Here are the steps to ask for permission.
Locate the info.plist file and add:
  1. 1.
    NSCameraUsageDescription
  2. 2.
    NSMicrophoneUsageDescription
  3. 3.
    NSPhotoLibraryUsageDescription

Setup API key

AmityUIKit requires an API key. You need a valid API key to begin using the UIKit. Please find your account API key in Amity Social Cloud Console.
After logging in Console:
  1. 1.
    Click Settings to expand the menu.
  2. 2.
    Select Security.
  3. 3.
    In the Security page, you can find the API key in the Keys section.
API key in Security page
Certainly! The provided code snippet demonstrates how to set up and authenticate using the Amity UIKit for Flutter. Let's break it down into a step-by-step guide:

Step 1: Initialize Amity SDK

First, you need to initialize the Amity SDK in your main function. This is crucial for setting up the SDK before your Flutter app starts running.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
AmitySLEUIKit().initUIKit("YOUR_API_KEY", "REGION");
runApp(const MyApp());
}
  • WidgetsFlutterBinding.ensureInitialized(): Ensures that Flutter bindings are initialized.
  • AmitySLEUIKit().initUIKit("YOUR_API_KEY", "REGION"): Initializes the Amity UIKit with your API key and region. Replace "YOUR_API_KEY" and "REGION" with the actual values.

Step 2: Wrap MaterialApp with AmitySLEProvider

In your main app widget (here, MyApp), wrap the MaterialApp with AmitySLEProvider. This provider is necessary for the Amity UIKit to function properly throughout your app.
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AmitySLEProvider(
child: Builder(builder: (context2) {
// Configuration and MaterialApp code goes here
}),
);
}
}

Step 3: Implement Authentication

In your InitialWidget class, implement a button to handle the login process with Amity.
ElevatedButton(
onPressed: () {
AmitySLEUIKit().registerDevice(context, "USER_IDENTIFIER");
},
child: const Text("Login to Amity"),
),
  • Replace "USER_IDENTIFIER" with the identifier of the user who is logging in.

Step 4: Navigating to UIKit Screens

The code provides examples of how to navigate to various screens provided by the Amity UIKit, like channel lists, chat rooms, and global feeds.
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const CommunityPage(),
));

Final Step: Running Your App

Once these steps are implemented, you can run your Flutter app. The Amity UIKit should be integrated and functioning according to the setup in your main.dart.
Remember to replace placeholders like "YOUR_API_KEY", "REGION", and "USER_IDENTIFIER" with actual values specific to your Amity UIKit setup.

Register device for push notifications

Registering your app for push notifications will require a device token as a parameter.
Amity's UIKit does not manage:
  • User-facing requests for push notifications and authorizations
  • The creation and refreshing of push notification tokens
It's up to your app to take those steps and pass the device token.
AmitySLEUIKit().registerNotification("asdasdasdasd",(isSuccess, error) {});

Unregister

In the event that your user logs out, you should explicitly unregister the user from the SDK as well, to prevent the current device from receiving any unnecessary or restricted data.
AmitySLEUIKit().unRegisterDevice();
Unregistering a device is a synchronous operation. Once theunregisterDevice method is called, the SDK disconnects from the server and wipes out user session.
Example main.dart
import 'package:amity_uikit_beta_service/amity_sle_uikit.dart';
import 'package:amity_uikit_beta_service/components/alert_dialog.dart';
import 'package:amity_uikit_beta_service/view/UIKit/social/my_community_feed.dart';
import 'package:amity_uikit_beta_service/view/social/global_feed.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:amity_uikit_beta_service/view/UIKit/social/create_community_page.dart';
import 'package:amity_uikit_beta_service/view/UIKit/social/explore_page.dart';
import 'package:amity_uikit_beta_service/view/UIKit/social/post_target_page.dart';
void main() {
///Step 1: Initialize amity SDK with the following function
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _apiKey = TextEditingController();
AmityRegion? _selectedRegion;
final TextEditingController _customUrl = TextEditingController();
@override
void initState() {
super.initState();
_loadPreferences();
}
Future<void> _loadPreferences() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_apiKey.text = prefs.getString('apiKey') ?? "";
print(_apiKey);
String? selectedRegionString = prefs.getString('selectedRegion');
if (selectedRegionString != null) {
_selectedRegion = AmityRegion.values.firstWhere(
(e) => e.toString() == selectedRegionString,
orElse: () => AmityRegion.sg,
);
}
if (_selectedRegion == AmityRegion.custom) {
_customUrl.text = prefs.getString('customUrl') ?? "";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Configuration'),
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
controller: _apiKey,
decoration: InputDecoration(
labelText: 'API Key',
border: OutlineInputBorder(),
),
),
SizedBox(height: 20),
Text('Select Region:'),
...AmityRegion.values.map((region) {
return RadioListTile<AmityRegion>(
title: Text(region.toString().split('.').last.toUpperCase()),
value: region,
groupValue: _selectedRegion,
onChanged: (AmityRegion? value) {
setState(() {
_selectedRegion = value;
if (value != AmityRegion.custom) {
_customUrl.text = ""; // Reset custom URL
}
});
},
);
}).toList(),
if (_selectedRegion == AmityRegion.custom) ...[
SizedBox(height: 20),
TextFormField(
decoration: InputDecoration(
labelText: 'Custom URL',
border: OutlineInputBorder(),
),
controller: _customUrl,
),
],
SizedBox(height: 40),
ElevatedButton(
child: Text('Initialize'),
onPressed: () async {
if (_apiKey != null &&
_selectedRegion != null &&
(_selectedRegion != AmityRegion.custom ||
_customUrl != null)) {
final prefs = await SharedPreferences.getInstance();
print(_apiKey);
await prefs.setString('apiKey', _apiKey.text);
await prefs.setString(
'selectedRegion', _selectedRegion.toString());
if (_selectedRegion == AmityRegion.custom &&
_customUrl != null) {
await prefs.setString('customUrl', _customUrl.text);
}
print("save pref");
await AmitySLEUIKit().initUIKit(
apikey: _apiKey.text,
region: _selectedRegion!,
customEndpoint: _customUrl.text);
// Navigate to the nextx page
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AmityApp()),
);
}
}),
],
),
),
);
}
}
class AmityApp extends StatelessWidget {
const AmityApp({super.key});
@override
Widget build(BuildContext context) {
return AmitySLEProvider(
child: Builder(builder: (context2) {
return UserListPage();
}),
);
}
}
class UserListPage extends StatefulWidget {
@override
_UserListPageState createState() => _UserListPageState();
}
class _UserListPageState extends State<UserListPage> {
List<String> _usernames = [];
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_loadUsernames();
}
_loadUsernames() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_usernames = prefs.getStringList('usernames') ?? [];
});
}
_addUsername() async {
if (_controller.text.isNotEmpty) {
SharedPreferences prefs = await SharedPreferences.getInstance();
_usernames.add(_controller.text);
prefs.setStringList('usernames', _usernames);
_controller.clear();
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User List'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Username',
border: OutlineInputBorder(),
),
),
),
ElevatedButton(
onPressed: _addUsername,
child: Text('Add Username'),
),
Expanded(
child: ListView.builder(
itemCount: _usernames.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_usernames[index]),
onTap: () async {
print("login");
///Step 3: login with Amity
await AmitySLEUIKit().registerDevice(
context: context,
userId: _usernames[index],
callback: (isSuccess, error) {
print("callback:${isSuccess}");
if (isSuccess) {
print("success");
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
SecondPage(username: _usernames[index]),
),
);
} else {
print(error);
AmityDialog().showAlertErrorDialog(
title: "Error", message: error.toString());
}
},
);
},
);
},
),
),
],
),
);
}
}
class SecondPage extends StatelessWidget {
const SecondPage({super.key, required this.username});
final String username;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Welcome, $username'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => ThirdPage(username: username),
),
);
},
child: Text('Social'),
),
ElevatedButton(
onPressed: () {
// Navigator.of(context).pushNamed('/third',
// arguments: {'username': username, 'feature': 'Chat'});
},
child: Text('Chat'),
),
],
),
),
);
}
}
class ThirdPage extends StatelessWidget {
const ThirdPage({super.key, required this.username});
final String username;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Social'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListTile(
title: Text('Register push notification'),
onTap: () {
// Navigate or perform action based on 'Global Feed' tap
AmitySLEUIKit().registerNotification("asdasdasdasd",
(isSuccess, error) {
return;
});
},
),
ListTile(
title: Text('unregister'),
onTap: () {
// Navigate or perform action based on 'Global Feed' tap
AmitySLEUIKit().unRegisterDevice();
},
),
ListTile(
title: Text('Global Feed'),
onTap: () {
// Navigate or perform action based on 'Global Feed' tap
Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
const Scaffold(body: GlobalFeedScreen()),
));
},
),
ListTile(
title: Text('User Profile'),
onTap: () {
// Navigate or perform action based on 'User Profile' tap
},
),
ListTile(
title: Text('Newsfeed'),
onTap: () {
// Navigate or perform action based on 'Newsfeed' tap
},
),
ListTile(
title: Text('Create Community'),
onTap: () {
// Navigate or perform action based on 'Newsfeed' tap
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scaffold(body: CreateCommunityPage()),
));
},
),
ListTile(
title: Text('Create Post'),
onTap: () {
// Navigate or perform action based on 'Newsfeed' tap
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scaffold(body: PostToPage()),
));
},
),
ListTile(
title: Text('My Community'),
onTap: () {
// Navigate or perform action based on 'Newsfeed' tap
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scaffold(body: MyCommunityPage()),
));
},
),
ListTile(
title: Text('Explore'),
onTap: () {
// Navigate or perform action based on 'Newsfeed' tap
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scaffold(body: CommunityPage()),
));
},
),
],
),
),
);
}
}
Last modified 2mo ago