Flutter3_Getx_Douyin跨端短视频直播|flutter3仿抖音实战

举报
yxybox 发表于 2024/03/26 22:09:55 2024/03/26
【摘要】 前段时间有给大家分享两款Flutter3.x开发桌面端IM聊天程序。又经过了半个多月的爆肝输出,flutter3.x仿抖音短视频+直播项目正式完结了。https://bbs.huaweicloud.com/blogs/421766https://bbs.huaweicloud.com/blogs/423160使用技术编辑器:Vscode技术框架:Flutter3.19.2+Dart3.3.0...

前段时间有给大家分享两款Flutter3.x开发桌面端IM聊天程序。又经过了半个多月的爆肝输出,flutter3.x仿抖音短视频+直播项目正式完结了。

https://bbs.huaweicloud.com/blogs/421766

https://bbs.huaweicloud.com/blogs/423160

未标题-2.png

未标题-1.png

使用技术

  • 编辑器: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

p4.gif

p6.gif

项目结构

360截图20240324084636378.png

flutter3_douyin 基于最新跨平台技术flutter3.19+dart3.3+getx+get_storage+media_kit开发手机端仿抖音app小视频直播实战项目。实现了抖音全屏式上下滑动视频、左右滑动切换页面模块,直播间进场/礼物动画,聊天等模块。

p7.gif

入口配置main.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:media_kit/media_kit.dart';

import 'utils/index.dart';

// 引入布局模板
import 'layouts/index.dart';

import 'binding/binding.dart';

// 引入路由管理
import 'router/index.dart';

void main() async {
  // 初始化get_storage
  await GetStorage.init();

  // 初始化media_kit
  WidgetsFlutterBinding.ensureInitialized();
  MediaKit.ensureInitialized();

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'FLUTTER3 DYLIVE',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFFFE2C55)),
        useMaterial3: true,
        // 修正windows端字体粗细不一致
        fontFamily: Platform.isWindows ? 'Microsoft YaHei' : null,
      ),
      home: const Layout(),
      // 全局绑定GetXController
      initialBinding: GlobalBindingController(),
      // 初始路由
      initialRoute: Utils.isLogin() ? '/' : '/login',
      // 路由页面
      getPages: routePages,
      // 错误路由
      // unknownRoute: GetPage(name: '/404', page: Error),
    );
  }
}

360截图20240324092525531.png

001360截图20240323230906999.png

002360截图20240323231117743.png

003360截图20240323231319575.png

003360截图20240323231930830.png

006360截图20240323232403006.png

008360截图20240323232606453.png

010360截图20240323232805940.png

012360截图20240323233615106.png

015360截图20240323233959299.png

019360截图20240323234416762.png

flutter自定义导航栏

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;
                });
              },
            ),
          ),
        ],
      );
    }),
  ),
);

flutter仿抖音滑动

p4.gif

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
              ],
            ),
          ],
        ),
      ),
    ],
  ),
);

flutter短视频拖拽进度条

// flutter滑动短视频模块  Q:282310962

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),),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
            /// 固定层
            // 红包
            Positioned(
              left: 15.0,
              top: MediaQuery.of(context).padding.top + 20,
              child: Container(
                height: 40.0,
                width: 40.0,
                decoration: BoxDecoration(
                  color: Colors.black12,
                  borderRadius: BorderRadius.circular(100.0),
                ),
                child: UnconstrainedBox(
                  child: Image.asset('assets/images/time-hb.png', width: 30.0, fit: BoxFit.contain,),
                ),
              ),
            ),
          ],
        ),
      ),
    ],
  ),
);

flutter直播模块

// 商品购买动效
Container(
  ...
),

// 加入直播间动效
const AnimationLiveJoin(
  joinQueryList: [
    {'avatar': 'assets/images/logo.png', 'name': 'andy'},
    {'avatar': 'assets/images/logo.png', 'name': 'jack'},
    {'avatar': 'assets/images/logo.png', 'name': '一条咸鱼'},
    {'avatar': 'assets/images/logo.png', 'name': '四季平安'},
    {'avatar': 'assets/images/logo.png', 'name': '叶子'},
  ],
),

// 送礼物动效
const AnimationLiveGift(
  giftQueryList: [
    {'label': '小心心', 'gift': 'assets/images/gift/gift1.png', 'user': 'Jack', 'avatar': 'assets/images/avatar/uimg2.jpg', 'num': 12},
    {'label': '棒棒糖', 'gift': 'assets/images/gift/gift2.png', 'user': 'Andy', 'avatar': 'assets/images/avatar/uimg6.jpg', 'num': 36},
    {'label': '大啤酒', 'gift': 'assets/images/gift/gift3.png', 'user': '一条咸鱼', 'avatar': 'assets/images/avatar/uimg1.jpg', 'num': 162},
    {'label': '人气票', 'gift': 'assets/images/gift/gift4.png', 'user': 'Flower', 'avatar': 'assets/images/avatar/uimg5.jpg', 'num': 57},
    {'label': '鲜花', 'gift': 'assets/images/gift/gift5.png', 'user': '四季平安', 'avatar': 'assets/images/avatar/uimg3.jpg', 'num': 6},
    {'label': '捏捏小脸', 'gift': 'assets/images/gift/gift6.png', 'user': 'Alice', 'avatar': 'assets/images/avatar/uimg4.jpg', 'num': 28},
    {'label': '你真好看', 'gift': 'assets/images/gift/gift7.png', 'user': '叶子', 'avatar': 'assets/images/avatar/uimg7.jpg', 'num': 95},
    {'label': '亲吻', 'gift': 'assets/images/gift/gift8.png', 'user': 'YOYO', 'avatar': 'assets/images/avatar/uimg8.jpg', 'num': 11},
    {'label': '玫瑰', 'gift': 'assets/images/gift/gift12.png', 'user': '宇辉', 'avatar': 'assets/images/avatar/uimg9.jpg', 'num': 3},
    {'label': '私人飞机', 'gift': 'assets/images/gift/gift16.png', 'user': 'Hison', 'avatar': 'assets/images/avatar/uimg10.jpg', 'num': 273},
  ],
),

// 直播弹幕+商品讲解
Container(
  margin: const EdgeInsets.only(top: 7.0),
  height: 200.0,
  child: Row(
    crossAxisAlignment: CrossAxisAlignment.end,
    children: [
      Expanded(
        child: ListView.builder(
          padding: EdgeInsets.zero,
          itemCount: liveJson[index]['message']?.length,
          itemBuilder: (context, i) => danmuList(liveJson[index]['message'])[i],
        ),
      ),
      SizedBox(
        width: isVisibleGoodsTalk ? 7 : 35,
      ),
      // 商品讲解
      Visibility(
        visible: isVisibleGoodsTalk,
        child: Column(
          ...
        ),
      ),
    ],
  ),
),

// 底部工具栏
Container(
  margin: const EdgeInsets.only(top: 7.0),
  child: Row(
    ...
  ),
),

作者:xiaoyan2017
链接:https://www.cnblogs.com/xiaoyan2017/p/18092224
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。