A Complete Guide to Create Video-Streaming App with Flutter (Using MUX)

Video Streaming App With flutter

Table of Contents

Note: This blog was originally published on 21st June 2021 and updated on 20th March 2023.

Quick Summary: The blog explains how to create a video streaming app with Flutter, covering basics of Flutter and Dart, and providing step-by-step instructions for implementing features like video player, authentication, and search functionality. It also discusses tools and libraries for easier app development.

Introduction:

Video streaming has turned into an inevitable trend that rules almost every popular app nowadays. Be it the Instagram Reels or Tik Tok; everyone is going gaga over such content. And, app makers are milking huge profits from this new trend of video streaming. 

But no matter how amazingly video streaming hooks the watchers, Hire Flutter developers use blood, sweat, and tears to handle the back-end’s technicalities to deliver what we see. 

This guide focuses on two major things, which are:

Key Takeaways
  • MUX provides tools to create high-quality video experiences.
  • Key elements of building a video streaming app with Flutter include plugin selection, UI design, video handling, and backend building.
  • Cloud-based services like Firebase and AWS can simplify backend building.
  • Thorough testing with tools like Flutter Driver is crucial.
  • Deployment through Firebase App Distribution or the Google Play Store is recommended.
  1. Creating Flutter App (Using Mux) For Video Streaming
  2. How to Play and Pause Video in Flutter Apps

Let’s begin! 

Creating Flutter App (Using Mux) For Video Streaming

Flutter Apps

What are the Main Steps Involved in Video Streaming?

  1. Encoding and decoding the video 
  2. Handling video database storage 
  3. Multiple Video Format Support 
  4. Distribution 

Since We Are Creating an App with MUX, let’s see what Mux is:

What is MUX?

MUX is an API-based video streaming service to handle the encoding and decoding of a video and distribute it to the users. In addition, using MUX lets you enjoy certain other features like GIFs, watermarks, subtitles, and thumbnails. Besides, MUX uses the data tracking API that helps in managing how exactly the video streaming has performed. However, MUX doesn’t take the responsibility of storing the video content. And, that’s why you will have to offer a URL where the video is stored. 

Getting Started with MUX

  1. Go to Mux.com and create your account.
  2. Once done, click on ‘Dashboard.’
  3. Add a video by visiting the ‘add a video file’ section to run the post request. 
  4.  Video will be stored in the assets section. 
  5. Generate API access token and enter the necessary details before clicking on Generate Token ID and Token Secret for API authentication. 
  6. Save these files in a private folder.

Essential Plugins to Build the App

  1. Dio – A powerful HTTP client for Dart that supports Global configuration, Request Cancellation, Timeout, Downloading, FormData, and Interceptors. 
  2. Intl – Offers internationalization and localization facilities like plurals and genders, bidirectional text, number and date formatting and phrasing, and message translation. 
  3. Video Player – Flutter plugin for web, Android, and iOS to playback video on a Widget surface. 

How to Build the Backend?

Video Streaming apps with flutter

Start by designing the backend of the app, followed by working on UI. Next, flutter developers focus on building a simple API server to send requests to Mux. You can write basic API server code in node.js.

Inside the root folder, you will have to create a file named .env with the following content.

MUX_TOKEN_ID=””

MUX_TOKEN_SECRET=””

Now, add your Token Secret and Token ID to this file so that it automatically picks up your credentials. 

Also, if you want to test it, run it on local machine node main.js

The backend of your Flutter App will consist of two main parts, i.e., model classes and Muz client, which are worked on as follows:

    1. Mux Client

      • Create MUXClient class inside a new file.
      • Create Dio Object
        class MUXClient {
         Dio _dio = Dio();
        }
      • Add a method
        class MUXClient {
          Dio _dio = Dio();
         initializeDio() {
            // initialize the dio here
         }
        }
      • Create a file that contains the constants

        // API for streaming a video
        const muxStreamBaseUrl = 'https://stream.mux.com';
        // Test video url provided by MUX
        const demoVideoUrl = 'https://storage.googleapis.com/muxdemofiles/mux-video.mp4';
        // API for streaming a video
        const muxStreamBaseUrl = 'https://stream.mux.com';
      • Storing video to Mux by creating a method and pass video URL to it.
        Future storeVideo({String videoUrl}) async {
        Response response;
        try {
        response = await _dio.post(
        "/assets",
        data: {
         "videoUrl": videoUrl,
          },
        );
        } catch (e) {
        print('Error starting build: $e');
        throw Exception('Failed to store video on MUX');
        }
        if (response.statusCode == 200) {
        VideoData videoData = VideoData.fromJson(response.data);
        String status = videoData.data.status;
        while (status == 'preparing') {
        print('processing...');
        await Future.delayed(Duration(seconds: 1));
        videoData = await checkPostStatus(videoId: videoData.data.id);
        status = videoData.data.status;
        }
        return videoData;
        }
        return null;
    2. Model Class

      Two main classes prevail in the model class, which are as follows:

      1. Asset Data 
      2. Video Data 

      Both Asset and Video data have further sub-classes, including Track, PlaybackId, and Data. 

    3. Home Page

      This page will contain a TextField, where you can add the URL of the video to upload it to Mux. Add ‘TextField’ and ‘RaisedButton’ for storing the video on Mux. 

    4. Preview Page

      You can preview the page to view the video and show the information related to the file. You can see a video player at the top of the page. Now VideoPlayerControler will be created and stored inside the InitState() of this class. Use Mux stream URL for loading and initializing the video controller. Inside the ‘Column’ create a video player to display the information. 

      Finally, the Flutter App is created for streaming videos. 

    5. Testing Video Streaming App

      Once your app is ready, it is time to test it. There are some tests to verify after you have successfully created the app. You can run app tests by using the command:

      flutter test

      How to Play and Pause Video in Flutter Apps

      Flutter Apps

      To play videos, the Flutter team provides a video_player plugin, which helps in playing the stored videos on your system (as an asset from the internet). 

      Video Player plugin by Flutter for iOS and Android are as follows:

      iOS – AVPlayer

      Android – ExoPlayer

      The plugin offered by Flutter helps in streaming video from the internet with the essential pause and play buttons. Here are the steps that you can follow to add it to your Flutter app. 

      1. Add video_player dependency

        Add the dependency to your pubspec.yaml.

        dependencies:

          flutter:

            sdk: flutter

          video_player:

      2. Add permissions to the app

        Update iOS and Android configurations for adding all necessary permissions to stream the videos from the internet. 

        For iOS

        NSAppTransportSecurity

          NSAllowsArbitraryLoads

        For Android 

      3. Create and initalize a VideoPlayerController

        VideoPlayerController allows you to connect different types of video content while controlling the playback. Initialize the controller to create a connection to the video and get the controller ready for playback. 

        How to create and initialize the VideoPlayerController? 

        Hire Flutter App Developers

        1. Create StatefulWidget with State Class
        2. Add a variable to State class (to store VideoPlayerController)
        3. Add a variable to State class to store the Future received back from VideoPlayerController.initialize
        4. In initState, create and initialize the controller
        5. Use dispose method to dispose the controller 

        Here’s the code to do so: 

        class VideoPlayerScreen extends StatefulWidget {  VideoPlayerScreen({Key? key}) : super(key: key);
          @override
           _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
        }
        class _VideoPlayerScreenState extends State {
          late VideoPlayerController _controller;
          late Future _initializeVideoPlayerFuture;
        @override
          void initState() {
            // Create an store the VideoPlayerController. The VideoPlayerController
            // offers several different constructors to play videos from assets, files,
            // or the internet.
          _controller = VideoPlayerController.network(
              ‘https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4’,
            );

            _initializeVideoPlayerFuture = _controller.initialize();
         super.initState();
          }

          @override
          void dispose() {
            // Ensure disposing of the VideoPlayerController to free up resources.
            _controller.dispose();
          super.dispose();
          }

          @override
          Widget build(BuildContext context) {
            // Complete the code in the next step.
            return Container();
          }
        }

      4. Video Player Displays

        VideoPlayer widget is now available to display the video initialized by VideoPlayerController. Now, wrap the VideoPlayer widget in the AspectRatio widget for setting the appropriate proportions of the video. 

        After the _initializeVideoPlayerFuture() is done, you must display the VideoPlayer widget. Now, use FutureBuilder to display the loading spinner. 

        // Use a FutureBuilder to display a loading spinner while waiting for the
        // VideoPlayerController to finish initializing.
        FutureBuilder(
          future: _initializeVideoPlayerFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              // If the VideoPlayerController has finished initialization, use
              // the data it provides to limit the aspect ratio of the video.
              return AspectRatio(
                aspectRatio: _controller.value.aspectRatio,
                // Use the VideoPlayer widget to display the video.
                child: VideoPlayer(_controller),
             );
            } else {
              // If the VideoPlayerController is still initializing, show a
              // loading spinner.
              return Center(child: CircularProgressIndicator());
            }
          },
        )

      5. Pause and Play the video

        Use the play() and pause() method to play and pause the video. Adding a FloatingActionButton will help you do that. 

        Here’s the code to follow:

        FloatingActionButton(
          onPressed: () {
            // Wrap the play or pause in a call to `setState`. This ensures the
            // correct icon is shown.
            setState(() {
              // If the video is playing, pause it.
              if (_controller.value.isPlaying) {
                _controller.pause();
              } else {
                // If the video is paused, play it.
                _controller.play();
              }
            });
          },
          // Display the correct icon depending on the state of the player.
          child: Icon(
            _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          ),
        )

At last, we really hope that by any chance this unique guide can help you to overcome hurdles to understand the video streaming process. At Your Team in India, we have a team of Flutter App Experts. If you want to hire Developers or have any questions on what all services we offer at Your team in India– Click here to contact us

Frequently Asked Questions

Q. How do I use MUX for live streaming?

To use MUX for live streaming:

  1. Create an account and set up a live stream in the MUX dashboard.
  2. Use MUX’s API or SDK to integrate the stream into your app or website.
  3. Push your video stream to the ingest URL using RTMP or HLS.
  4. Monitor the stream and view analytics in the dashboard.
Q. Which API is used in live streaming?

Some commonly used APIs for live streaming include WebRTC, RTMP, HLS, MPEG-DASH, and RTSP.

Q. How do you implement MUX in Flutter?

To implement MUX in Flutter, you can follow these general steps:

  1. Add the MUX SDK dependency to your Flutter project.
  2. Configure the MUX SDK by initializing it with your MUX API keys.
  3. Create a new live stream in the MUX dashboard.
  4. Start the live stream by pushing your video stream to the specified ingest URL using a supported streaming protocol such as RTMP or HLS.
  5. Use MUX’s player API to integrate the live stream into your Flutter app.
Q. How do I make a video streaming app for Android?

To make a video streaming app for Android:

  1. Choose a development platform or framework like Java, Kotlin or Flutter.
  2. Define your app’s features like user registration, video playback and social sharing.
  3. Choose a video streaming service or API like YouTube, Vimeo or AWS Elemental MediaLive.
  4. Integrate the video streaming service or API using their SDKs or APIs.
  5. Design the user interface using Android app development tools like Android Studio and XML.
  6. Test and debug your app.
  7. Publish your app on the Google Play Store or another app store.

Mangesh Gothankar

Seasoned technology professional with over 19 years of experience leading technology innovation and execution with startups and MNCs. Experience in hiring and creating multiple world-class technology teams. Results-oriented with a passion for technology, recognized for successfully planning and executing major initiatives.

Rewards & Recognition   :