David Serrano
David Serrano

Follow

David Serrano

Follow
Create a High-Quality Live Streaming App with Flutter

Create a High-Quality Live Streaming App with Flutter

David Serrano's photo
David Serrano
·Apr 6, 2023·

5 min read

In this article, I will be explaining how to incorporate multimedia streaming into your Flutter application.

This type of technology is usually quite expensive, not only do you need to have a deep understanding of all the low-level protocols, but you also require to have high-performance servers that handle all that traffic quickly and securely.

Fortunately, there are companies that offer this service, so all you have to do is focus on implementing it. ZEGOCLOUD is one such company that reached out to me. Having witnessed firsthand how quick and effortless their solution is, they kindly agreed to sponsor this article so that I can provide you with this tutorial.

It is worth mentioning that what is explained in this tutorial can be done without paying anything, just go to their website and register. You will be able to create test applications to test their service without the need to add any credit card. Once you've done that, we're going to start the tutorial on how to add streaming features to your Flutter app.

How to add streaming functionality to a Flutter app

Once you are inside the dashboard, press the button that says "Create your project" to start creating your project.

In the next step we must specify the use case that we want to cover, in this case, we will choose "Live Streaming":

Then we must add a name to the project, you can put the name you prefer.

Then we will be asked if we want to use the UIKits or the SDK. The advantage of UIKits over the SDK is that they already contain everything needed to implement the functionality, including the graphical interface. For this tutorial, we want to add streaming functionality as quickly and easily as possible, so we'll choose "Start with UIKits":

Once all these data have been entered, the project creation will begin.

Once created, we will choose the "For Flutter" option:

Now click on the button located at the bottom right of the screen, titled "Save & Start to integrate":

Now you will see two values that are essential in order to connect your Flutter application with the project that you just created in the dashboard: the AppID and the AppSign. Write them down because you will need them later.

Create the Flutter application

Now we will proceed to create the Flutter application:

flutter create flutter_live_streaming

Now we will install zego_uikit_prebuilt_live_streaming, which is the ZEGOCLOUD library in charge of carrying out the streaming. We are also going to install uuid to be able to generate identifiers quickly:

flutter pub add zego_uikit_prebuilt_live_streaming uuid

Open the project with your preferred IDE, let's do some preliminary tweaking to make sure everything will work fine.

First, open android/app/build.gradle and modify the following parameters:

  • compileSdkVersion 33

  • minSdkVersion 22

  • targetSdkVersion 33

We must also define the permissions that the application will use. To do this add them inside the manifest tag in AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Now we will adjust the iOS project. Open ios/Podfile and add the following to the end of the file:

# [...]

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)

    # Add the following block:
    target.build_configurations.each do |config|
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        'PERMISSION_CAMERA=1',
        'PERMISSION_MICROPHONE=1',
      ]
    end
    # End of the block to add.
  end
end

We must also define the permissions that the app will use in ios/Runner/Info.plist:

<key>NSCameraUsageDescription</key>
<string>We require camera access to connect to a live</string>
<key>NSMicrophoneUsageDescription</key>
<string>We require microphone access to connect to a live</string>

Ok, after making all these settings, we can now start writing our Dart code. Replace the contents of lib/main.dart with the following:

import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:zego_uikit_prebuilt_live_streaming/zego_uikit_prebuilt_live_streaming.dart';

void main() {
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Live Streaming',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MainScreen(),
    );
  }
}

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  // This will be the streaming identifier. Ideally, in your system
  // you should create a room management system,
  // and generate the identifier there.
  final String _id = 'my_live_streaming';

  // This variable will define if we are the host or not.
  // In your room system you should create the logic to be able to
  // designate the hosts and viewers. For now, to be able to test
  // the functionality quickly, we give it a value of true
  // (we will be the creator of the streaming).
  final bool _isHost = true;

  // We will now define two variables, one for the user's ID
  // and one for their name. As with the previous variables,
  // we'll give them a random value so that we can quickly
  // test the functionality. In your system you could use the
  // identifier you already have to identify users and the user's own name.
  late final String _userId;
  late final String _userName;

  @override
  void initState() {
    super.initState();

    // We use the uuid package to generate random ids.
    _userId = const Uuid().v4();
    _userName = 'user_${const Uuid().v4().substring(0, 7)}';
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      // Use the UIKit ZegoUIKitPrebuiltLiveStreaming,
      // it will automatically take care of painting the
      // interface without us having to detail it.
      child: ZegoUIKitPrebuiltLiveStreaming(
        // Now you must add the AppID and the AppSign that you
        // have previously obtained in the ZEGOCLOUD dashboard
        // in order to connect this application with that project.
        appID: your_app_id,
        appSign: 'your_app_sign',
        userID: _userId,
        userName: _userName,
        liveID: _id,
        config: _isHost
            ? ZegoUIKitPrebuiltLiveStreamingConfig.host()
            : ZegoUIKitPrebuiltLiveStreamingConfig.audience(),
      ),
    );
  }
}

If you have done everything right, you will be able to start your streaming in the application. Now you can try running this same code but changing the value of the _isHost variable to false, to simulate the audience. You will see that you will be able to see and hear what the streamer is broadcasting.

Conclusion

As you can see, adding the option to stream audio and video to a specific audience is very easy and simple using the pre-built UIKits. Thanks to ZEGOCLOUD for sponsoring this article, don't forget to visit their website to get more information about their products and services.

I hope this tutorial has been useful to you, see you in the next article!

Did you find this article valuable?

Support David Serrano by becoming a sponsor. Any amount is appreciated!

See recent sponsors | Learn more about Hashnode Sponsors