
A social app I was brought in to help with had a problem that looked like a network problem and wasn’t one. Every time a video scrolled into view, the feed sat on a black frame for three to five seconds before the first video frame appeared. The team had already tried the usual suspects: compressing the videos, re-encoding into different formats, and finally settling on HLS streaming. Each change bought a small improvement, and none of them fixed it. The tell was that the wait was identical on Wi-Fi and on 5G, on old phones and on the newest models. When the network isn’t the bottleneck, the code is.
This is the story of what was actually wrong, the fix, and the handful of ideas behind it.
The setup
The app is a Flutter social platform with a mixed feed, a scrolling list where a single post might be plain text, a photo, a photo carousel, or one or more videos, sometimes several of those combined. Think of a feed where every card can be a different shape. That variety matters later; it’s the reason the obvious off-the-shelf fixes didn’t fit.
The piece that mattered for performance is the video player. In Flutter, a video player is driven by a small object called a controller; it’s the thing that opens the video file, talks to the network, decodes frames, and tracks whether the video is playing or paused. Creating a controller and pointing it at a video is not free. It takes time and memory.
The symptom, precisely
Here’s what was happening, slowed down. The moment a video card became visible, the app did four jobs back to back, all on the spot, all while the user was already staring at the card:
It allocated a brand-new controller, told that controller where the video lived, asked the network for the first chunk of video, and built the on-screen widgets to show it. Four jobs, and not one of them had started before the user arrived. The three-to-five-second wait wasn’t the network being slow, it was the user watching the app begin its work from a cold start, every single time.
The naive design that shipped first
The original code created one controller per feed item, built inside the widget’s initState , the function that runs the instant a piece of UI comes to life. Initialisation, data-source setup, the network fetch, and layout all happened on the same frame the item became visible. In plain terms: each video card was responsible for bootstrapping itself at the worst possible moment, the moment you were already looking at it.
Buried in that same setup was a quiet disaster:
cacheConfiguration: const BetterPlayerCacheConfiguration(
useCache: true,
maxCacheSize: 500000 * 1024 * 1024, // ~488 TB. A typo in production.
maxCacheFileSize: 500000 * 1024 * 1024,
),
That cache size resolves to roughly 488 terabytes. No phone has 488 terabytes of disk. A single extra zero in the wrong column had turned a sane cache limit into a request for half a petabyte. It wasn’t the bug causing the delay, but it’s the kind of thing that hides for months because nobody re-reads a constant once it’s been merged.
Time, not space, is the bottleneck
At any given moment, the user is looking at exactly one post. The next two or three are about to be looked at. Everything else can stay cold and untouched. So the question stops being how do we make initialization faster and becomes how do we make sure initialization already happened before the user gets here.
If the network and decode work starts before the user arrives, then “showing a video” stops meaning “create the player, buffer it, and play” and starts meaning, simply, “play.” The expensive part moves off the critical path and into the time the user spends on the previous post. That’s the whole trick it’s the same move as pre-loading the next cue on a soundboard while the current track is still playing, so nothing scrambles once you hit go.
The shape of the fix: a sliding window of controllers
You can’t pre-warm everything that’s what the 488 TB cache was implicitly trying to do, and it would blow up memory. The right structure is a sliding window: a small, fixed-size pool of pre-warmed controllers that follows your scroll position.
Picture a rail of cards. The card you’re on is active. A few cards ahead are warm already initialized, ready to play the instant you reach them. A few behind are kept warm too, in case you scroll back. Everything outside that band is cold. As you scroll forward, the window slides: the card entering from the front gets initialized, and the oldest card falling off the back gets disposed its controller torn down and its memory released. The window is a fixed-width frame that the content slides through, so memory stays bounded no matter how long the feed is.

In the implementation, the window is configured with a few knobs: how many posts to keep warm behind you (preloadBackward, default 3), how many ahead (preloadForward, default 3), and the total window size (windowSize, default 8), with a guard that the warm band must fit inside the window. As you cross from one post into the next, the window advances one slot, initializing the new edge and disposing the old one.
Why couldn’t I just drop in an existing plugin?
There are good open-source preloaders for exactly this the TikTok / Reels vertical-video pattern is well-trodden. The problem is that almost all of them bake in one assumption: one video per post, addressed by a single flat index. Post 0, post 1, post 2, each holding exactly one video.
This feed broke that assumption on day one. A post here is mixed media it can hold text, images, audio, a video, or a horizontal carousel mixing several of those. The data shape didn’t fit.
First instinct was to fake it: flatten every post’s media into one long list and pad the gaps with null entries for text-only posts. That lasted about an hour before the index math started drifting and controllers were warming for posts that had already scrolled past. Grouping by post instead of by video was the actual fix, not the workaround.
So rather than fight a tool built for a different world, I forked one whose abstraction was right even though its data model wasn’t custom_preload_videos and restructured the window to match the real content. The change, at its core, was moving from a flat list of videos to a structure grouped by post:
// Upstream: a flat list of videos
List<String> _videoUrls = [];
List<CustomVideoController> _preloadWindow = [];
Future<void> scroll(int index) { /* … */ }
// The fork: videos grouped by the post they belong to
List<List<String>> _videoUrlGroups = [];
Map<int, List<CustomVideoController>> _preloadWindow = {};
Future<void> scroll(int postIndex, int mediaIndex) { /* … */ }
Same plugin, same sliding-window idea different data model. Now a “slot” in the window isn’t one video; it’s a group of controllers belonging to one post, and scrolling is addressed by two coordinates: which post, and which piece of media within it.
The adapter that kept the host app clean
The plugin is deliberately ignorant of which video player you use. It defines an abstract interface called CustomVideoController , a contract listing what any controller must be able to do (initialize, play, pause, dispose, report whether it’s ready) without saying how. This is the adapter pattern: the plugin states the shape of the plug, and you supply something that fits the socket.
The app uses BetterPlayer under the hood, so I wrote a roughly 60-line adapter that wraps a BetterPlayerController and presents it through the plugin’s interface:
class BetterPlayerCustomController extends CustomVideoController {
final String _url;
late BetterPlayerController _controller;
@override
Future<void> initialize() async {
final dataSource = BetterPlayerDataSource(
BetterPlayerDataSourceType.network,
_url,
cacheConfiguration: const BetterPlayerCacheConfiguration(useCache: true),
);
_controller = BetterPlayerController(
const BetterPlayerConfiguration(
autoPlay: false, // the preloader owns playback
autoDispose: false, // the preloader owns lifecycle
looping: true,
fit: BoxFit.cover,
),
betterPlayerDataSource: dataSource,
);
await _controller.setupDataSource(dataSource); // ← this warms the stream
}
}

Two settings carry the whole separation of concerns. autoPlay: false and autoDispose: false tell BetterPlayer to do nothing on its own not to start playing, not to clean itself up. The preloader is now the single owner of when things play and when they’re torn down. The setupDataSource call is what actually warms the HLS stream ahead of time the work that used to happen in front of the user.
The payoff of routing everything through the interface: the host app never touches the plugin’s internals, and if the team wants to swap BetterPlayer for a different video library tomorrow, only this one file changes.
The mixed-media problem, and how the two worlds were bridged
There’s a subtle bookkeeping issue once posts can be text-only or image-only. The preloader only cares about videos, so its world is a list of video groups. The feed, on the other hand, cares about every post, including the ones with no video at all. The two number their items differently feed position 3 might be the first video group, because positions 0 through 2 were text and images.
The fix is two small translation maps kept in the host app that convert between “position in the feed” and “position in the preloader’s video list,” built as posts stream in:
final Map<int, int> _postIndexToGroupIndex = {};
final Map<int, List<String>> _postIndexToVideoUrls = {};
for (int i = 0; i < newItems.length; i++) {
final overallPostIndex = currentPostCount + i;
final videoUrlsInPost = newItems[i].result?.feed?.mediaUrl
?.where((url) => determineFileType(url) == 'video')
.toList() ?? [];
if (videoUrlsInPost.isNotEmpty) {
_postIndexToGroupIndex[overallPostIndex] =
_videoUrlGroups.length + newUrlGroups.length;
_postIndexToVideoUrls[overallPostIndex] = videoUrlsInPost;
newUrlGroups.add(videoUrlsInPost);
}
}
Text-only and image-only posts simply don’t get a preloader slot, and because the maps track the mapping explicitly, skipping them never throws the indexing off. The video machinery never has to know about text and image posts, and the feed never has to know about controllers.
Two-level visibility: deciding what’s “active”
A post can become the active item for two different reasons, and the preloader is intentionally indifferent to which. Vertically, a post scrolling into view crosses a visibility threshold and becomes active; scrolling away, it pauses. Horizontally, swiping between media inside a post changes which controller should be playing. Both funnel into the same single call.
VisibilityDetector(
key: Key(item.result?.feed?.id.toString() ?? '$index'),
onVisibilityChanged: (info) {
final groupIndex = _postIndexToGroupIndex[index];
if (groupIndex == null) return;
if (info.visibleFraction > 0.7) {
_preloadVideos?.scroll(groupIndex, 0); // mostly on screen → play
} else if (info.visibleFraction < 0.3) {
_preloadVideos?.getControllerAt(groupIndex, 0)?.pause(); // mostly gone → pause
}
},
child: /* the post UI */,
);

A post that’s more than 70% on screen starts playing its first video; one that’s dropped below 30% pauses. Horizontal swipes within a post route through the page-change callback to the right media. Either way, the preloader is told only what the active item now is, never why it changed which keeps the two scroll axes from tangling together.
To keep the experience sane, only one video is ever playing at a time: when a new video starts, the preloader pauses every other controller in the window, tracking the currently-playing source so it never double-plays.
Bounded memory and feeds that never end
Two more pieces make it production-ready. First, memory: because the window disposes controllers as they fall off the back, the controller count stays capped at the window size no matter how far the user scrolls. Second, infinite scroll: when the user gets within a few posts of the end of what’s loaded (a configurable threshold, default 5), the preloader asks the app for more video groups and appends them, guarded by a flag so two fetches can’t fire at once. The feed feels endless; the memory doesn’t.
The results
I’ll be honest about the measurement here, because it matters: this shipped against a perceived-performance brief, not a benchmark suite. We optimized for what the user feels, and the before/after is stark.
The three-to-five-second black-frame wait before playback became near-instant on scroll, because the work that caused the wait now happens before you arrive. The memory footprint went from unbounded controller growth to a fixed ceiling at the window size. The app’s video widget shed roughly 120 lines of initialization, lifecycle, and app-state bookkeeping the preloader owns all of that now, so the UI code got simpler as a side effect. And the 488-terabyte cache typo went away in the process. Putting real numbers on it with proper instrumentation is the obvious next step.
What actually mattered
The lesson that’ll stick with me isn’t really about video players. “Make it faster” and “make it already done” are different engineering problems with different fixes compression and re-encoding were both answers to the first question, and the wait was caused by the second. Once that clicked, the actual code change was almost boring.
The plugin fork is the part I’d repeat without hesitation. Forking custom_preload_videos cost an afternoon, because the abstraction a sliding window behind a clean controller interface was already right. All I owed it was a different data shape. And I still think about the 488TB constant sitting untouched in production for who knows how long, because nobody re-reads a cache size once it ships. It’s a small, permanent reminder to grep your own defaults occasionally, not just the ones you’re actively touching.
One more specific thing, since it’s the number people usually ask about: eight works here because these posts are big enough that a couple of warm neighbors on each side covers how fast people actually scroll. A pure vertical-video feed can often run on three. Match the window to your content, not to whatever number felt safe.
What I’d tell the next person making this call
Don’t initialize on visibility. Initialize on approach. The most expensive work in an interactive app should happen in the slack time before the user needs it, not in the instant they’re waiting on it. That single reframe from “make it faster” to “make it already done” is worth more than any amount of compression or re-encoding.
When you reach for an open-source tool, separate the abstraction from the data model. The plugin here had exactly the right shape a sliding window behind a clean controller interface but assumed one video per post, which my feed violated. Forking it was the right move, and it was cheap, precisely because the abstraction was sound; all I changed was the data structure underneath. The interface is the contract; the implementation is yours to own.
Treat your window size as content-dependent, not a magic number. Eight works here because these posts are big bigger than a single swipe so a few warm on each side covers the user’s reach. A pure full-screen TikTok feed can often run on three. Match the warm band to how fast people actually move through your content.
And audit your “set and forget” constants. A single zero in the wrong column quietly rented us a petabyte of disk that didn’t exist. The configuration values nobody re-reads are exactly the ones that hide the expensive mistakes.
Built on top of the open-source custom_preload_videos plugin (aman246149/flutter-plugin). Credit to the original author for a clean abstraction the fork was about data shape, not design.