This is a continuation of the blog series: "Building a Youtube Clone with Strapi and Flutter". It is suggested that you read Part 1 to understand how we got to this stage.
For reference purposes, here's the outline of this blog series:
In this Part 2, we'll learn how to set up a new Flutter project, configure permissions, create the app services, and state management to handle real-time functionalities and UI updates.
To get started, let's set up a new Flutter project, configure the development environment, and install the required dependencies for this project.
Create a new flutter project in the terminal by running the commands below.
flutter create youtube_clone
cd youtube_clone
flutter run
First, we need to configure the permissions to grant users access to the internet, read and write external storage, and use the camera.
For Android, open the android/app/src/main/AndroidManifest.xml
file and add the necessary permissions to your existing AndroidManifest.xml
file:
1<manifest xmlns:android="http://schemas.android.com/apk/res/android">
2 <!-- Permission for internet access -->
3 <uses-permission android:name="android.permission.INTERNET"/>
4
5 <!-- Permissions for accessing external storage -->
6 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
7 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
8
9 <!-- Permission for camera access -->
10 <uses-permission android:name="android.permission.CAMERA"/>
11
12 <application
13 ...
14 android:usesCleartextTraffic="true"
15 ...>
16 ...
17 </application>
18</manifest>
Then for iOS, open the ios/Runner/Info.plist
file and add the necessary permissions into your existing ios/Runner/Info.plist
file:
1...
2<dict>
3 <key>NSPhotoLibraryUsageDescription</key>
4 <string>Allow access to photo library</string>
5 <key>NSCameraUsageDescription</key>
6 <string>Allow access to camera</string>
7 <key>NSMicrophoneUsageDescription</key>
8 <string>Allow access to microphone</string>
9 ...
10</dict>
11</plist>
After making these changes, rebuild and run your app.
Next, add the necessary dependencies for this project. We'll install the following dependencies:
Run the command below on your terminal from the root directory of your Flutter project to install the dependencies:
1flutter pub add http video_player web_socket_channel provider image_picker socket_io_client path flutter_secure_storage
Finally, configure the project assets files that will be used in this project. Create a new directory named assets
in the root directory of your project. In the assets
directory, create an images
directory to keep the images. Then download the YouTube logo into that directory.
Open the pubspec.yaml
file from the root directory of your project, locate the assets
section, and add assets to your application:
1assets:
2 - assets/images/YouTube_logo.png
Lastly, create a utils
folder in the lib
folder, inside the utils
folder create a new getter.dart
file and add the code snippets:
1import 'dart:io';
2import 'package:flutter/foundation.dart' show kIsWeb;
3
4String getBaseUrl() {
5 if (kIsWeb) {
6 return 'http://localhost:1337';
7 } else if (Platform.isAndroid) {
8 return 'http://10.0.2.2:1337';
9 } else if (Platform.isIOS) {
10 return 'http://localhost:1337';
11 } else {
12 return 'http://localhost:1337';
13 }
14}
The getBaseUrl()
function checks which device the app is running on and returns the appropriate host for that device. This ensures that our application works on any platform.
Now that you have set up your Flutter project, configured the permissions, add assets, and installed the required project dependencies, let's proceed to creating the app services to make API requests to your Strapi backend.
Create a new folder named services
in the lib
directory. In the services
directory, create a new file named video_service.dart
. Define a VideoService
class and add a fetchVideos
method to fetch video data from your Strapi backend:
1import 'dart:io';
2import 'package:http/http.dart' as http;
3import 'dart:convert';
4import 'package:flutter_secure_storage/flutter_secure_storage.dart';
5import 'package:youtube_clone/utils/getter.dart';
6
7class VideoService {
8 static const String populateQuery =
9 'populate[comments][populate][user][populate][profile_picture]=profile_picture&populate[thumbnail]=*&populate[video_file]=*&populate[likes]=*&populate[views]=*&populate[comments][populate]=*&populate[uploader][populate]=profile_picture&populate[uploader][populate]=subscribers';
10 final _storage = const FlutterSecureStorage();
11
12 Future<List<dynamic>> fetchVideos() async {
13 final response =
14 await http.get(Uri.parse('${getBaseUrl()}/api/videos?$populateQuery'));
15
16 if (response.statusCode == 200) {
17 final Map<String, dynamic> responseData = json.decode(response.body);
18
19 // Extract the list of videos from the 'data' field
20 return responseData['data'] as List<dynamic>;
21 } else {
22 throw Exception('Failed to load videos');
23 }
24 }
25
26 Future<Map<String, dynamic>> fetchVideo(String documentId) async {
27 final response = await http
28 .get(Uri.parse('$getBaseUrl()/api/videos/$documentId/$populateQuery'));
29
30 if (response.statusCode == 200) {
31 final Map<String, dynamic> responseData = json.decode(response.body);
32
33 // Extract the list of videos from the 'data' field
34 return responseData['data'] as Map<String, dynamic>;
35 } else {
36 throw Exception('Failed to load videos');
37 }
38 }
39}
In the above code VideoService
we defined two global variables, populateQuery
for all the populate queries we'll use to populate all the relations models in your Video collection. The fetchVideos
method sends a GET
request to fetch all videos, while fetchVideo
retrieves a single video by its documentId
. Both methods use the populateQuery
for all the required data retrieval, including comments, user information, thumbnails, etc.
Next, update the VideoService
to define a new method to handle the video uploading. Also since this is an authenticated action we'll need a JWT token, so we'll define a new method to extract the token from the device's local storage (the logic for saving the token will be handled when implementing authentication):
1 //...
2 Future<String?> _getAuthToken() async {
3 return await _storage.read(key: 'auth_token');
4 }
5
6 Future<void> uploadVideoContent(File videoFile, File thumbnailFile,
7 String title, String description, String userId) async {
8 try {
9 final baseUrl = getBaseUrl();
10
11 final videoId = await uploadFile(videoFile, 'video');
12
13 final thumbnailId = await uploadFile(thumbnailFile, 'image');
14
15 await createVideoEntry(
16 baseUrl, videoId, thumbnailId, title, description, userId);
17 } catch (e) {
18 print('Error occurred: $e');
19 }
20 }
21
22 Future<String> uploadFile(File file, String fileType) async {
23 final uri = Uri.parse('${getBaseUrl()}/api/upload');
24
25 var request = http.MultipartRequest('POST', uri);
26 request.files.add(await http.MultipartFile.fromPath('files', file.path));
27
28 var response = await request.send();
29 if (response.statusCode == 201) {
30 final responseBody = await response.stream.bytesToString();
31 final jsonResponse = jsonDecode(responseBody);
32 return jsonResponse[0]['id'].toString();
33 } else {
34 throw Exception('Failed to upload $fileType');
35 }
36 }
37
38 Future<void> createVideoEntry(String baseUrl, String videoId,
39 String thumbnailId, String title, String description, userId) async {
40 final uri = Uri.parse('$baseUrl/api/videos');
41 final token = await _getAuthToken();
42 final response = await http.post(
43 uri,
44 headers: {
45 'Content-Type': 'application/json',
46 'Authorization': 'Bearer $token',
47 },
48 body: jsonEncode({
49 "data": {
50 "title": title,
51 "description": description,
52 "video_file": videoId,
53 "thumbnail": thumbnailId,
54 "uploader": userId
55 }
56 }),
57 );
58
59 if (response.statusCode == 201) {
60 print('Video entry created successfully');
61 } else {
62 print('Failed to create video entry: ${response.body}');
63 throw Exception('Failed to create video entry');
64 }
65 }
66 //...
In these code snippets, we've added some new methods to our VideoService
class to handle uploading videos and creating entries. The _getAuthToken
method grabs the auth token from secure storage (we'll need this for some requests).
The uploadVideoContent
method is the main player here. It manages the whole process of uploading a video file and its thumbnail, then creates a new entry in the backend. It uses the uploadFile
method to send the files to the server and get their IDs back.
Then we have the createVideoEntry
method. This takes all the info we've collected, video ID, thumbnail ID, title, description, and user's ID, and creates a new video entry in our Strapi backend. It uses the auth token we retrieved earlier. We've also added error handling throughout to catch and log any problems that might pop up during the upload and creation process.
Lastly, add the following methods to the VideoService
class to handle the like, views, comment and subscribe requests to your Strapi backend:
1 //...
2 Future<void> likeVideo(String videoId) async {
3 final token = await _getAuthToken();
4 final response = await http.put(
5 Uri.parse('${getBaseUrl()}/api/videos/$videoId/like'),
6 headers: {
7 'Content-Type': 'application/json',
8 'Authorization': 'Bearer $token',
9 },
10 );
11
12 if (response.statusCode != 200) {
13 throw Exception('Failed to like video');
14 }
15 }
16
17 Future<void> increaseViews(String videoId) async {
18 final token = await _getAuthToken();
19
20 final response = await http.put(
21 Uri.parse('${getBaseUrl()}/api/videos/$videoId/increment-view'),
22 headers: {
23 'Content-Type': 'application/json',
24 'Authorization': 'Bearer $token',
25 },
26 );
27
28 if (response.statusCode != 200) {
29 throw Exception(
30 'Failed to increase views: ${response.reasonPhrase} (${response.statusCode})');
31 }
32 }
33
34 Future<void> commentOnVideo(
35 String videoId, String comment, String userId) async {
36 final token = await _getAuthToken();
37 final response = await http.post(
38 Uri.parse('${getBaseUrl()}/api/comments?populate=*'),
39 headers: {
40 'Content-Type': 'application/json',
41 'Authorization': 'Bearer $token',
42 },
43 body: jsonEncode({
44 "data": {'text': comment, "user": userId, "video": videoId}
45 }),
46 );
47
48 if (response.statusCode != 200) {
49 throw Exception(
50 'Failed to post comment: ${response.body}');
51 }
52 }
53
54 Future subscribeToChannel(int userId) async {
55 final uri = Uri.parse('${getBaseUrl()}/api/videos/$userId/subscribe');
56 final token = await _getAuthToken();
57 final response = await http.put(
58 uri,
59 headers: {
60 'Content-Type': 'application/json',
61 'Authorization': 'Bearer $token',
62 },
63 );
64 if (response.statusCode == 200) {
65 print('Subscription created successfully');
66 } else {
67 print('Failed to create subscription: ${response.body}');
68 throw Exception('Failed to create subscription');
69 }
70 }
71 //...
In this part of the code, we've defined a few more methods to VideoService
class to handle some common video interactions such as liking, increasing views, commenting, and subscribing to a channel.
First, we've defined the likeVideo
method to send a request to the server to like a specific video. We use the auth
token to make sure the user is logged in. Then the increaseViews
method to increase the view count for a video. Again, we're using the auth token to keep things secure. Lastly, define the commentOnVideo
method to allow users to post comments on videos. It sends the video ID, the comment text, and the user ID to the server.
To allow users to sign-up to create a channel and log in. You'll need to create a user service. Create a new user_service.dart
file in lib/services
directory and add the code snippets below:
1import 'dart:io';
2import 'package:http/http.dart' as http;
3import 'package:youtube_clone/services/video_service.dart';
4import 'dart:convert';
5import 'package:youtube_clone/utils/getter.dart';
6
7class UserService {
8 Future<String?> login(String email, String password) async {
9 final response = await http.post(
10 Uri.parse('${getBaseUrl()}/api/auth/local'),
11 headers: {'Content-Type': 'application/json'},
12 body: jsonEncode({
13 'identifier': email,
14 'password': password,
15 }),
16 );
17
18 if (response.statusCode == 200) {
19 final data = json.decode(response.body);
20 return data['jwt'];
21 } else {
22 return null;
23 }
24 }
25
26 Future<Map?> me(String jwtToken) async {
27 final response = await http.get(
28 Uri.parse('${getBaseUrl()}/api/users/me?populate=role,profile_picture,'),
29 headers: {
30 'Content-Type': 'application/json',
31 "Authorization": 'Bearer $jwtToken',
32 },
33 );
34 if (response.statusCode == 200) {
35 final data = json.decode(response.body);
36 return data;
37 } else {
38 return null;
39 }
40 }
41
42 Future<String?> signup(File profilePicturefile, String email, String username,
43 String password) async {
44 try {
45 final profilePictureid =
46 await VideoService().uploadFile(profilePicturefile, 'image');
47
48 final response = await http.post(
49 Uri.parse('${getBaseUrl()}/api/auth/local/register'),
50 headers: {'Content-Type': 'application/json'},
51 body: jsonEncode({
52 'username': username,
53 'password': password,
54 "email": email,
55 'profile_picture': profilePictureid
56 }),
57 );
58
59 if (response.statusCode == 200) {
60 final data = json.decode(response.body);
61 return data['jwt'];
62 } else {
63 return null;
64 }
65 } catch (e) {
66 print('Error occurred: $e');
67 }
68 return null;
69 }
70}
In the above code snippets, we created a new UserService
class to handle user-related operations. We designed a login
method that sends a request to the Strapi authentication endpoint to log in to a user using their email
and password
. If it works, we get back a JWT token that we can use for future requests.
Then we defined a me
method that fetches the current user's info from the server, including their role and profile picture. Lastly, we defined a signup
method, which takes a profile picture file along with the user's email, username, and password. First, it uploads the profile picture using our VideoService
. Then it sends all this info to the server to create a new user account. If everything goes well, we get back a JWT token for the new user.
Now that we've created the App services, we need to keep track of the data change over time and make sure all parts of our app stay in sync. We'll be using the Flutter state management package called Provider.
To handle the real-time functionalities of the application, like users being able to see uploaded videos, comments, likes, and subscriptions in real-time, we need to create a Socket provider to listen to all the events we defined in your collections and update the UI accordingly. Create a new socket_provider.dart
file in the provider's directory and add the code snippets below:
1import 'package:flutter/material.dart';
2import 'package:socket_io_client/socket_io_client.dart' as IO;
3import 'package:youtube_clone/utils/getter.dart';
4
5class SocketProvider with ChangeNotifier {
6 IO.Socket? _socket;
7 bool _isConnected = false;
8
9 bool get isConnected => _isConnected;
10
11 void connect(BuildContext context) {
12 _socket = IO.io(getBaseUrl(), {
13 'transports': ['websocket'],
14 'autoConnect': false,
15 });
16
17 _socket?.on('connect', (_) {
18 _isConnected = true;
19 notifyListeners();
20 });
21
22 _socket?.on('disconnect', (_) {
23 _isConnected = false;
24 notifyListeners();
25 });
26
27 // Listen for video events and update the VideoProvider
28 _socket?.on('video.created', (_) => notifyListeners());
29 _socket?.on('video.updated', (_) => notifyListeners());
30 _socket?.on('video.deleted', (_) => notifyListeners());
31 _socket?.on('comment.created', (_) => notifyListeners());
32 _socket?.on('user.updated', (_) => notifyListeners());
33 _socket?.on('user.created', (_) => notifyListeners());
34 _socket?.connect();
35 }
36
37 void disconnect() {
38 _socket?.disconnect();
39 }
40}
In the above code, we created a SocketProvider
class using Flutter's ChangeNotifier
to manage a WebSocket connection with the Strapi server. This setup will allow your application to receive real-time updates from the Video, Comment, and User collections.
To manage the state in our app for all the video-related data and operations, create a VideoProvider
class. Create a new directory named providers
in your lib
directory. Then create a video_provider.dart
in our providers
folder and add the code below:
1import 'dart:io';
2import 'package:flutter/material.dart';
3import 'package:provider/provider.dart';
4import 'package:youtube/providers/socket_provider.dart';
5import 'package:youtube/services/video_service.dart';
6
7class VideoProvider with ChangeNotifier {
8 List _videos = [];
9 Map _video = {};
10
11 List get videos => _videos;
12
13 VideoProvider(BuildContext context) {
14 final socketProvider = Provider.of<SocketProvider>(context, listen: false);
15 socketProvider.addListener(_handleSocketEvents);
16 }
17
18 void _handleSocketEvents() {
19 fetchVideos();
20 }
21
22 Future fetchVideos() async {
23 try {
24 _videos = await VideoService().fetchVideos();
25 notifyListeners();
26 } catch (error) {
27 print("Error fetching videos: $error");
28 }
29 }
30
31 Future fetchVideo(String documentId) async {
32 try {
33 _video = await VideoService().fetchVideo(documentId);
34 notifyListeners();
35 } catch (error) {
36 print("Error fetching videos: $error");
37 }
38 }
39
40 Future likeVideo(String videoId) async {
41 try {
42 await VideoService().likeVideo(videoId);
43 notifyListeners();
44 } catch (error) {
45 print("Error liking video: $error");
46 }
47 }
48
49 Future increaseViews(String videoId) async {
50 try {
51 await VideoService().increaseViews(videoId);
52 notifyListeners();
53 } catch (error) {
54 print("Error increasing views: $error");
55 }
56 }
57
58 Future commentOnVideo(String videoId, String comment, String userId) async {
59 try {
60 await VideoService().commentOnVideo(videoId, comment, userId);
61 notifyListeners();
62 } catch (error) {
63 print("Error commenting on video: $error");
64 }
65 }
66
67 Future uploadFile(
68 File imageFile, File videoFile, String title, String description, String userId) async {
69 try {
70 await VideoService().uploadVideoContent(
71 videoFile,
72 imageFile,
73 title,
74 description,
75 userId
76 );
77 notifyListeners();
78 } catch (error) {
79 print("Error uploading file: $error");
80 }
81 }
82
83 Future subscribeToChannel(int documentId) async {
84 try {
85 await VideoService().subscribeToChannel(documentId);
86 notifyListeners();
87 } catch (error) {
88 print("Error subscribing to channel: $error");
89 }
90 }
91}
Here the fetchVideos
and fetchVideo
methods get videos from our VideoService
, update the local _videos
and _video
lists, and then call notifyListeners()
which tells the rest of our app that the data has changed and the UI needs to update. Also, the likeVideo
, increaseViews
,commentOnVideo
, uploadFile
, and subscribeToChannel
methods call their corresponding VideoService
methods and updates the UI.
Create a new user_provider.dart
file in the providers folder and add the code snippets below:
1import 'dart:io';
2import 'package:flutter/material.dart';
3import 'package:flutter_secure_storage/flutter_secure_storage.dart';
4import 'package:youtube/services/user_service.dart';
5
6class UserProvider with ChangeNotifier {
7 final _storage = const FlutterSecureStorage();
8 String? _token;
9 String? _message;
10 Map<String, dynamic>? _user;
11
12 String? get token => _token;
13 String? get message => _message;
14 Map<String, dynamic>? get user => _user;
15
16 Future<void> login(String email, String password) async {
17 try {
18 _token = await UserService().login(email, password);
19 if (_token != null) {
20 _user = (await UserService().me(_token!)) as Map<String, dynamic>?;
21 await _storage.write(key: 'auth_token', value: _token);
22 _message = null;
23 notifyListeners();
24 } else {
25 _message = 'Invalid email or password';
26 notifyListeners();
27 }
28 } catch (e) {
29 _message = 'Failed to login. Please try again later.';
30 notifyListeners();
31 }
32 }
33
34 Future<void> signup(File profilePicturefile, String email, String username,
35 String password) async {
36 try {
37 _token = await UserService()
38 .signup(profilePicturefile, email, username, password);
39 if (_token != null) {
40 _user = (await UserService().me(_token!)) as Map<String, dynamic>?;
41 await _storage.write(key: 'auth_token', value: _token);
42 _message = null;
43 notifyListeners();
44 } else {
45 _message = 'Signup failed. Please check your details and try again.';
46 notifyListeners();
47 }
48 } catch (e) {
49 print(e);
50 _message = 'Failed to sign up. Please try again later.';
51 notifyListeners();
52 }
53 }
54
55 Future<void> loadToken() async {
56 _token = await _storage.read(key: 'auth_token');
57 notifyListeners();
58 }
59
60 Future<void> logout() async {
61 _token = null;
62 _user = {};
63 await _storage.delete(key: 'auth_token');
64 notifyListeners();
65 }
66}
In the code provided above, we created a UserProvider
class using Flutter's ChangeNotifier
to manage user authentication and state. It interacts with a UserService
to perform login
, and signup
, and fetch user details.
Now update your main.dart
file with the code snippets below:
1import 'package:flutter/material.dart';
2import 'package:provider/provider.dart';
3import 'package:youtube_clone/providers/socket_provider.dart';
4import 'package:youtube_clone/providers/user_provider.dart';
5import 'package:youtube_clone/providers/video_provider.dart';
6
7void main() {
8 runApp(
9 MultiProvider(
10 providers: [
11 ChangeNotifierProvider(create: (_) => SocketProvider()),
12 ChangeNotifierProvider(create: (_) => UserProvider()),
13 ChangeNotifierProvider(
14 create: (context) => VideoProvider(context),
15 ),
16 ],
17 child: const MyApp(),
18 ),
19 );
20}
21
22class MyApp extends StatelessWidget {
23 const MyApp({super.key});
24
25 @override
26 Widget build(BuildContext context) {
27 // Connect to the socket when the app starts
28 Provider.of<SocketProvider>(context, listen: false).connect(context);
29
30 return MaterialApp(
31 title: 'YouTube Clone',
32 theme: ThemeData(
33 brightness: Brightness.dark,
34 primaryColor: Colors.black,
35 scaffoldBackgroundColor: Colors.black,
36 appBarTheme: const AppBarTheme(
37 backgroundColor: Colors.black,
38 elevation: 0,
39 iconTheme: IconThemeData(color: Colors.white),
40 titleTextStyle: TextStyle(
41 color: Colors.white,
42 fontSize: 20,
43 fontWeight: FontWeight.bold,
44 ),
45 ),
46 iconTheme: const IconThemeData(color: Colors.white),
47 textTheme: const TextTheme(
48 bodyLarge: TextStyle(color: Colors.white),
49 bodyMedium: TextStyle(color: Colors.white70),
50 titleMedium: TextStyle(color: Colors.white),
51 titleSmall: TextStyle(color: Colors.white70),
52 ),
53 chipTheme: ChipThemeData(
54 backgroundColor: Colors.grey[850],
55 labelStyle: const TextStyle(color: Colors.white),
56 secondaryLabelStyle: const TextStyle(color: Colors.white),
57 brightness: Brightness.dark,
58 padding: const EdgeInsets.symmetric(horizontal: 8),
59 ),
60 cardColor: Colors.grey[900],
61 dividerColor: Colors.grey[700],
62 ),
63 home: const Center(child: Text("My YouTube Clone")),
64 );
65 }
66}
In the above code, we integrated the SocketProvider
, UserProvider
, and VideoProvider
using MultiProvider
, ensuring these services are available across the app. We also initialized a socket connection at the app launch by invoking the connect
method from the SocketProvider
in the MyApp
widget.
We also configured the MaterialApp
with a dark theme to create a consistent, YouTube-like UI throughout the application.
We're done with Part 2 of this blog series. Stay tuned for Part 3, where we'll continue this tutorial by building the frontend with Flutter and consuming the APIs to implement a functional YouTube clone application.
In Part 2 of this tutorial series, we've learned how to set up a new Flutter project, configure permissions, create the app services, and configure Flutter state management to handle real-time functionalities and UI updates.
The code for this project is available on Github.
In the last part of this blog series, we will learn how to build the app UI with Flutter.
I am Software Engineer and Technical Writer. Proficient Server-side scripting and Database setup. Agile knowledge of Python, NodeJS, ReactJS, and PHP. When am not coding, I share my knowledge and experience with the other developers through technical articles