百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

基于flutter3.x跨端仿抖音app实战|flutter-douyin短视频直播

liuian 2025-05-21 14:58 16 浏览

#精品长文创作季#

又经过了半个多月的爆肝输出,全新原创的flutter3_douyin短视频直播项目完结了。

目前已经实现好的功能有首页、短视频、直播、聊天、我的等几个页面模块。

实现了类似抖音全屏沉浸式滑动效果(上下滑动视频、左右切换页面模块)。

实现了左右滑动的同时,顶部状态栏+Tab菜单+底部bottomNavigationBar导航栏三者联动效果。

技术栈

  • 编辑器:Vscode
  • 技术框架:Flutter3.19.2+Dart3.3.0
  • 路由/状态管理:get: ^4.6.6
  • 本地缓存:get_storage: ^2.1.1
  • 图片预览插件:photo_view: ^0.14.0
  • 刷新加载:easy_refresh^3.3.4
  • toast轻提示:toast^0.3.0
  • 视频套件:media_kit: ^1.1.10+1

为了考虑在windows端调试方便,目前视频播放器使用media_kit套件。

在开发的过程中,遇到了不少问题,最后都顺利解决了。

项目结构目录

预览图

flutter3底部导航菜单

使用 bottomNavigationBar 组件实现页面模块切换。通过getx全局状态来联动控制底部导航栏背景颜色。导航栏中间图标/图片按钮,使用了 Positioned 组件定位实现功能。

return Scaffold(
  backgroundColor: Colors.grey[50],
  body: pageList[pageCurrent],
  // 底部导航栏
  bottomNavigationBar: Theme(
    // Flutter去掉BottomNavigationBar底部导航栏的水波纹
    data: ThemeData(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      hoverColor: Colors.transparent,
    ),
    child: Obx(() {
      return Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              border: Border(top: BorderSide(color: Colors.black54, width: .1)),
            ),
            child: BottomNavigationBar(
              backgroundColor: bottomNavigationBgcolor(),
              fixedColor: FStyle.primaryColor,
              unselectedItemColor: bottomNavigationItemcolor(),
              type: BottomNavigationBarType.fixed,
              elevation: 1.0,
              unselectedFontSize: 12.0,
              selectedFontSize: 12.0,
              currentIndex: pageCurrent,
              items: [
                ...pageItems
              ],
              onTap: (index) {
                setState(() {
                  pageCurrent = index;
                });
              },
            ),
          ),
          // 自定义底部导航栏中间按钮
          Positioned(
            left: MediaQuery.of(context).size.width / 2 - 15,
            top: 0,
            bottom: 0,
            child: InkWell(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Icon(Icons.tiktok, color: bottomNavigationItemcolor(centerDocked: true), size: 32.0,),
                  Image.asset('assets/images/applogo.png', width: 32.0, fit: BoxFit.contain,)
                  // Text('直播', style: TextStyle(color: bottomNavigationItemcolor(centerDocked: true), fontSize: 12.0),)
                ],
              ),
              onTap: () {
                setState(() {
                  pageCurrent = 2;
                });
              },
            ),
          ),
        ],
      );
    }),
  ),
);
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../styles/index.dart';
import '../../controllers/page_video_controller.dart';

// 引入pages页面
import '../pages/index/index.dart';
import '../pages/video/index.dart';
import '../pages/live/index.dart';
import '../pages/message/index.dart';
import '../pages/my/index.dart';

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

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {
  PageVideoController pageVideoController = Get.put(PageVideoController());

  // page索引
  int pageCurrent = 0;
  // page页面
  List pageList = [const Index(), const FVideo(), const FLiveList(), const Message(), const My()];
  // tabs选项
  List pageItems = [
    const BottomNavigationBarItem(
      icon: Icon(Icons.home_outlined),
      label: '首页'
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.play_arrow_outlined),
      label: '短视频'
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.live_tv_rounded, color: Colors.transparent,),
      label: ''
    ),
    BottomNavigationBarItem(
      icon: Stack(
        alignment: const Alignment(4, -2),
        children: [
          const Icon(Icons.messenger_outline),
          FStyle.badge(1)
        ],
      ),
      label: '消息'
    ),
    BottomNavigationBarItem(
      icon: Stack(
        alignment: const Alignment(1.5, -1),
        children: [
          const Icon(Icons.person_outline),
          FStyle.badge(0, isdot: true)
        ],
      ),
      label: '我'
    )
  ];

  // 底部导航栏背景色
  Color bottomNavigationBgcolor() {
    int index = pageCurrent;
    int pageVideoTabIndex = pageVideoController.pageVideoTabIndex.value;
    Color color = Colors.white;
    if(index == 1) {
      if([1, 2, 3].contains(pageVideoTabIndex)) {
        color = Colors.white;
      }else {
        color = Colors.black;
      }
    }
    return color;
  }
  // 底部导航栏颜色
  Color bottomNavigationItemcolor({centerDocked = false}) {
    int index = pageCurrent;
    int pageVideoTabIndex = pageVideoController.pageVideoTabIndex.value;
    Color color = Colors.black54;
    if(index == 1) {
      if([1, 2, 3].contains(pageVideoTabIndex)) {
        color = Colors.black54;
      }else {
        color = Colors.white60;
      }
    }else if(index == 2 && centerDocked) {
      color = FStyle.primaryColor;
    }
    return color;
  }

  // ...
}

flutter3短视频滑动效果

return Scaffold(
  extendBodyBehindAppBar: true,
  appBar: AppBar(
    forceMaterialTransparency: true,
    backgroundColor: [1, 2, 3].contains(pageVideoController.pageVideoTabIndex.value) ? null : Colors.transparent,
    foregroundColor: [1, 2, 3].contains(pageVideoController.pageVideoTabIndex.value) ? Colors.black : Colors.white,
    titleSpacing: 1.0,
    leading: Obx(() => IconButton(icon: Icon(Icons.menu, color: tabColor(),), onPressed: () {},),),
    title: Obx(() {
      return TabBar(
        controller: tabController,
        tabs: pageTabs.map((v) => Tab(text: v)).toList(),
        isScrollable: true,
        tabAlignment: TabAlignment.center,
        overlayColor: MaterialStateProperty.all(Colors.transparent),
        unselectedLabelColor: unselectedTabColor(),
        labelColor: tabColor(),
        indicatorColor: tabColor(),
        indicatorSize: TabBarIndicatorSize.label,
        unselectedLabelStyle: const TextStyle(fontSize: 16.0, fontFamily: 'Microsoft YaHei'),
        labelStyle: const TextStyle(fontSize: 16.0, fontFamily: 'Microsoft YaHei', fontWeight: FontWeight.w600),
        dividerHeight: 0,
        labelPadding: const EdgeInsets.symmetric(horizontal: 10.0),
        indicatorPadding: const EdgeInsets.symmetric(horizontal: 5.0),
        onTap: (index) {
          pageVideoController.updatePageVideoTabIndex(index); // 更新索引
          pageController.jumpToPage(index);
        },
      );
    }),
    actions: [
      Obx(() => IconButton(icon: Icon(Icons.search, color: tabColor(),), onPressed: () {},),),
    ],
  ),
  body: Column(
    children: [
      Expanded(
        child: Stack(
          children: [
            /// 水平滚动模块
            PageView(
              // 自定义滚动行为(支持桌面端滑动、去掉滚动条槽)
              scrollBehavior: PageScrollBehavior().copyWith(scrollbars: false),
              scrollDirection: Axis.horizontal,
              controller: pageController,
              onPageChanged: (index) {
                pageVideoController.updatePageVideoTabIndex(index); // 更新索引
                setState(() {
                  tabController.animateTo(index);
                });
              },
              children: [
                ...pageModules
              ],
            ),
          ],
        ),
      ),
    ],
  ),
);

短视频底部有一条播放进度条。

return Container(
  color: Colors.black,
  child: Column(
    children: [
      Expanded(
        child: Stack(
          children: [
            /// 垂直滚动模块
            PageView.builder(
              // 自定义滚动行为(支持桌面端滑动、去掉滚动条槽)
              scrollBehavior: PageScrollBehavior().copyWith(scrollbars: false),
              scrollDirection: Axis.vertical,
              controller: pageController,
              onPageChanged: (index) async {
                ...
              },
              itemCount: videoList.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    // 视频区域
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      bottom: 0,
                      child: GestureDetector(
                        child: Stack(
                          children: [
                            // 短视频插件
                            Visibility(
                              visible: videoIndex == index,
                              child: Video(
                                controller: videoController,
                                fit: BoxFit.cover,
                                // 无控制条
                                controls: NoVideoControls,
                              ),
                            ),
                            // 播放/暂停按钮
                            StreamBuilder(
                              stream: player.stream.playing,
                              builder: (context, playing) {
                                return Visibility(
                                  visible: playing.data == false,
                                  child: Center(
                                    child: IconButton(
                                      padding: EdgeInsets.zero,
                                      onPressed: () {
                                        player.playOrPause();
                                      },
                                      icon: Icon(
                                        playing.data == true ? Icons.pause : Icons.play_arrow_rounded,
                                        color: Colors.white70,
                                        size: 70,
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                        onTap: () {
                          player.playOrPause();
                        },
                      ),
                    ),
                    // 右侧操作栏
                    Positioned(
                      bottom: 15.0,
                      right: 10.0,
                      child: Column(
                        ...
                      ),
                    ),
                    // 底部信息区域
                    Positioned(
                      bottom: 15.0,
                      left: 10.0,
                      right: 80.0,
                      child: Column(
                        ...
                      ),
                    ),
                    // 播放mini进度条
                    Positioned(
                      bottom: 0.0,
                      left: 10.0,
                      right: 10.0,
                      child: Visibility(
                        visible: videoIndex == index && position > Duration.zero,
                        child: Listener(
                          child: SliderTheme(
                            data: const SliderThemeData(
                              trackHeight: 2.0,
                              thumbShape: RoundSliderThumbShape(enabledThumbRadius: 4.0), // 调整滑块的大小
                              // trackShape: RectangularSliderTrackShape(), // 使用矩形轨道形状
                              overlayShape: RoundSliderOverlayShape(overlayRadius: 0), // 去掉Slider默认上下边距间隙
                              inactiveTrackColor: Colors.white24, // 设置非活动进度条的颜色
                              activeTrackColor: Colors.white, // 设置活动进度条的颜色
                              thumbColor: Colors.pinkAccent, // 设置滑块的颜色
                              overlayColor: Colors.transparent, // 设置滑块覆盖层的颜色
                            ),
                            child: Slider(
                              value: sliderValue,
                              onChanged: (value) async {
                                // debugPrint('当前视频播放时间$value');
                                setState(() {
                                  sliderValue = value;
                                });
                                // 跳转播放时间
                                await player.seek(duration * value.clamp(0.0, 1.0));
                              },
                              onChangeEnd: (value) async {
                                setState(() {
                                  sliderDraging = false;
                                });
                                // 继续播放
                                if(!player.state.playing) {
                                  await player.play();
                                }
                              },
                            ),
                          ),
                          onPointerMove: (e) {
                            setState(() {
                              sliderDraging = true;
                            });
                          },
                        ),
                      ),
                    ),
                    // 视频播放时间
                    Positioned(
                      bottom: 90.0,
                      left: 10.0,
                      right: 10.0,
                      child: Visibility(
                        visible: sliderDraging,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(position.label(reference: duration), style: const TextStyle(color: Colors.white, fontSize: 16.0, fontWeight: FontWeight.w600),),
                            Container(
                              margin: const EdgeInsets.symmetric(horizontal: 7.0),
                              child: const Text('/', style: TextStyle(color: Colors.white54, fontSize: 10.0,),),
                            ),
                            Text(duration.label(reference: duration), style: const TextStyle(color: Colors.white54, fontSize: 16.0, fontWeight: FontWeight.w600),),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    ],
  ),
);

Ok,限于篇幅,flutter3仿抖音短视频项目就先分享到这里。

相关推荐

软件测试/测试开发丨Pytest 自动化测试框架(五)

公众号搜索:TestingStudio霍格沃兹测试开发的干货都很硬核测试报告在项目中是至关重要的角色,一个好的测试报告:可以体现测试人员的工作量;开发人员可以从测试报告中了解缺陷的情况;测试经理可以...

python爬虫实战之Headers信息校验-Cookie

一、什么是cookie上期我们了解了User-Agent,这期我们来看下如何利用Cookie进行用户模拟登录从而进行网站数据的爬取。首先让我们来了解下什么是Cookie:Cookie指某些网站为了辨别...

软件测试 | 结合Allure生成测试报告

简介测试报告在项目至关重要,测试人员可以在测试报告中体现自己的工作量,开发人员可以从测试报告中了解缺陷的情况,测试经理可以从测试报告中看到测试人员的执行情况及测试用例的覆盖率,项目负责人可以通过测...

使用FUSE挖掘文件上传漏洞(文件上传漏洞工具)

关于FUSEFUSE是一款功能强大的渗透测试安全工具,可以帮助广大研究人员在最短的时间内迅速寻找出目标软件系统中存在的文件上传漏洞。FUSE本质上是一个渗透测试系统,主要功能就是识别无限制可执行文件上...

第42天,我终于意识到,爬虫这条路,真的好艰难

昨天说到学爬虫的最初四行代码,第四行中的print(res.text),我没太懂。为啥最后的输出的结果,不是显示百度网页全部的源代码呢?这个世界上永远不缺好心人。评论区的大神告诉我:因为只包含静态h...

详解Pytest单元测试框架,轻松搞定自动化测试实战

pytest是目前企业里面使用最多、最流行的Python的单元测试框架,那我们今天就使用这个框架来完成一个网易163邮箱登录的自动化实战案例。下面我们先把我们案例需要的工具进行相关的介绍:01pyt...

干货|Python大佬手把手带你破解哔哩哔哩网滑动验证(上篇)

/1前言/有爬虫经验的各位小伙伴都知道,正常我们需要登录才能获取信息的网站,是比较难爬的。原因就是在于,现在各大网站为了反爬,与爬虫机制斗智斗勇,一般的都加入了图片验证码、滑动验证码之类的干扰,让...

Python 爬虫-如何抓取需要登录的网页

本文是Python爬虫系列第四篇,前三篇快速入口:Python爬虫-开启数据世界的钥匙Python爬虫-HTTP协议和网页基础Python爬虫-使用requests和B...

使用Selenium实现微博爬虫:预登录、展开全文、翻页

前言想实现爬微博的自由吗?这里可以实现了!本文可以解决微博预登录、识别“展开全文”并爬取完整数据、翻页设置等问题。一、区分动态爬虫和静态爬虫1、静态网页静态网页是纯粹的HTML,没有后台数据库,不含程...

从零开始学Python——使用Selenium抓取动态网页数据

1.selenium抓取动态网页数据基础介绍1.1什么是AJAX  AJAX(AsynchronouseJavaScriptAndXML:异步JavaScript和XML)通过在后台与服务器进...

PHP自动测试框架Top 10(php单元测试工具)

对于很多PHP开发新手来说,测试自己编写的代码是一个非常棘手的问题。如果出现问题,他们将不知道下一步该怎么做。花费很长的时间调试PHP代码是一个非常不明智的选择,最好的方法就是在编写应用程序代码之前就...

10款最佳PHP自动化测试框架(php 自动化测试)

为什么测试如此重要?PHP开发新手往往不会测试自己编写的代码,我们中的大多数通过不断测试我们刚刚所编写浏览器窗口的新特性和功能来进行检测,但是当事情出现错误的时候我们往往不知道应该做些什么。为我们的代...

自动化运维:Selenium 测试(seleniumbase搭建自动化测试平台)

本文将以Buddy中的Selenium测试流水线示例,来看看自动化测试就是如此简单易用!Selenium是一套用于浏览器测试自动化的工具。使用Buddy专有服务,您可以直接在Buddy中运行Selen...

Selenium自动化测试(selenium自动化测试工具)

Selenium是一系列基于web的自动化测试工具。它提供了一系列测试函数,用于支持Web自动化测试。这些函数非常灵活,它们能够通过多种方式定位界面元素,并可以将预期结果与系统实际表现进行比较。作为一...

技术分享 | Web自动化之Selenium安装

本文节选自霍格沃兹测试开发学社内部教材Web应用程序的验收测试常常涉及一些手工任务,例如打开一个浏览器,并执行一个测试用例中所描述的操作。但是手工执行的任务容易出现人为的错误,也比较费时间。因此,将...