Creating a Dynamic YouTube Video List Using Flutter and YouTubePlayer

Developing a dynamic list of YouTube videos in a Flutter application involves several key steps, including setting up a database, creating a backend to serve the data, and building the frontend to display the videos. Here’s a detailed guide on how I approached this project using the youtube_player_flutter package.

Step 1: Setting Up the Flutter Project

To begin, I created a new Flutter project. This is a straightforward process using the Flutter command-line tools:

flutter create youtube_video_list
cd youtube_video_list

With the project initialized, I configured the necessary dependencies in the pubspec.yaml file. Specifically, I added the youtube_player_flutter package to handle YouTube video playback:

yamlCopy codedependencies:
  flutter:
    sdk: flutter
  youtube_player_flutter: ^8.0.0
  http: ^0.13.3

Step 2: Setting Up the Database

Next, I set up a MySQL database using PHPMyAdmin to store the YouTube video IDs. This involved creating a table named videosapp with a single column to store YouTube IDs.

sqlCopy codeCREATE TABLE `videosapp` (
  `youtubeid` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `videosapp`
ADD PRIMARY KEY (`youtubeid`);

COMMIT;

This table serves as a repository for the YouTube video IDs that will be dynamically fetched and displayed in the Flutter app.

Step 3: Creating the Backend

To fetch the video data, I developed a PHP script that connects to the MySQL database, retrieves the YouTube IDs, and outputs them in JSON format. Below is the PHP code for this functionality.

phpCopy code<?php
header('Content-Type: application/json');

// Database connection details
static $DB_SERVER = "your_server";
static $DB_NAME = "your_database_name";
static $USERNAME = "your_username";
static $PASSWORD = "your_password";

// Create connection
$conn = new mysqli($DB_SERVER, $USERNAME, $PASSWORD, $DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT youtubeid FROM videosapp";
$result = $conn->query($sql);

$spacecrafts = array();

while ($row = $result->fetch_array()) {
    array_push($spacecrafts, array("youtubeid" => $row['youtubeid']));
}

echo json_encode(array_reverse($spacecrafts));

$conn->close();
?>

This script connects to the database, retrieves all the YouTube IDs, and returns them as a JSON array.

Step 4: Fetching Data in Flutter

With the backend in place, the next step was to fetch this data in the Flutter application. I used the http package to make a GET request to the PHP script and retrieve the video IDs.

dartCopy codeimport 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

class VideoList extends StatefulWidget {
  @override
  _VideoListState createState() => _VideoListState();
}

class _VideoListState extends State<VideoList> {
  List<YoutubePlayerController> _controllers = [];

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

  _fetchVideos() async {
    final response = await http.get(Uri.parse('http://yourserver.com/your_php_script.php'));

    if (response.statusCode == 200) {
      List videos = json.decode(response.body);
      setState(() {
        _controllers = videos.map<YoutubePlayerController>((video) {
          return YoutubePlayerController(
            initialVideoId: video['youtubeid'],
            flags: YoutubePlayerFlags(
              autoPlay: false,
            ),
          );
        }).toList();
      });
    } else {
      throw Exception('Failed to load videos');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('YouTube Video List'),
      ),
      body: ListView.builder(
        itemCount: _controllers.length,
        itemBuilder: (context, index) {
          return YoutubePlayer(
            controller: _controllers[index],
            showVideoProgressIndicator: true,
            progressIndicatorColor: Colors.red,
          );
        },
      ),
    );
  }
}

In this code, I created a stateful widget VideoList that fetches video data from the PHP script during initialization. The _fetchVideos method makes an HTTP GET request and parses the response into a list of YoutubePlayerController objects.

Step 5: Building the UI

The UI consists of a ListView.builder that creates a list of YoutubePlayer widgets. Each widget is initialized with a controller created from the fetched video IDs.

dartCopy codebody: ListView.builder(
  itemCount: _controllers.length,
  itemBuilder: (context, index) {
    return YoutubePlayer(
      controller: _controllers[index],
      showVideoProgressIndicator: true,
      progressIndicatorColor: Colors.red,
    );
  },
),

The ListView.builder dynamically creates the list of video players, ensuring efficient performance even with a large number of videos.

Conclusion

This approach demonstrates how to create a dynamic YouTube video list in Flutter using the youtube_player_flutter package. By storing video IDs in a MySQL database, serving them via a PHP backend, and fetching them in Flutter, we achieve a robust and scalable solution. This method can be extended with additional features such as search functionality, video metadata, and user interactions to enhance the user experience.

stevenmathew_279
stevenmathew_279
Articles: 3