Flutter抖音功能集成插件douyin的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter抖音功能集成插件douyin的使用

功能

支持的API

注册抖音SDK

Future<String> registerDouyinApp({required String apiKey});

授权登录

⚠️scopeKey多个类型需要用英文逗号隔开,如trial.whitelist,user_info

Future<String> authorLogin({required String scopeKey});

监听授权登录回调

Stream<DouYinResp> respStream();

使用

Android: 在项目的android目录中的build.gradle里添加抖音SDK的仓库地址

repositories {
    google()
    mavenCentral()
    maven { url 'https://artifact.bytedance.com/repository/AwemeOpenSDK' }
}

iOS: 在项目的ios目录中的Podfile文件中导入抖音SDK

⚠️:需要注释掉use_frameworks!,因为抖音SDK有静态引用

pod 'DouyinOpenSDK'
  • info.plistQueried URL Schemes添加以下几个值
douyinopensdk douyinliteopensdk douyinsharesdk snssdk1128
  • TARGETS->Info->URL Types*中添加URL_Schemes为注册的抖音Client Key,用于处理授权登录后返回自己的App

  • 项目的AppDelegate.swift添加回调监听

import UIKit
import Flutter
import DouyinOpenSDK

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, DouyinOpenSDKLogDelegate {
    override func application(
            _ application: UIApplication,
            didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        DouyinOpenSDKApplicationDelegate.sharedInstance().logDelegate = self
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        let result = DouyinOpenSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation] as? String)
        return result;
    }

    func onLog(_ logInfo: String) {
        NSLog("douyin log %@", logInfo)
    }
}

示例

import 'dart:async';

import 'package:douyin/douyin.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _initState = "none";
  String _code = "";
  final _douyinPlugin = Douyin();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
    authorResultState();
  }

  void authorResultState() {
    _douyinPlugin.respStream().listen((event) {
      setState(() {
        _code = event.authCode;
      });
    });
  }

  Future<void> initPlatformState() async {
    String initState;
    initState = await _douyinPlugin.registerDouyinApp(apiKey: '');
    if (!mounted) return;

    setState(() {
      _initState = initState;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Center(
              child: Text('Running on: $_initState\n----$_code'),
            ),
            Center(
              child: ElevatedButton(
                  onPressed: () {
                    _douyinPlugin.authorLogin(
                      scopeKey: "trial.whitelist,user_info",
                    );
                  },
                  child: const Text('授权登录')),
            )
          ],
        ),
      ),
    );
  }
}

更多关于Flutter抖音功能集成插件douyin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter抖音功能集成插件douyin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中集成类似抖音功能的插件时,虽然没有一个官方的“douyin”插件,但你可以通过组合多个Flutter插件和自定义代码来实现类似的功能。以下是一个简要的示例,展示如何使用Flutter和一些流行的第三方插件来构建类似抖音的核心功能,比如视频播放、用户认证、评论系统等。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加必要的依赖。这里我们会用到chewie(用于视频播放)、firebase_auth(用于用户认证)、cloud_firestore(用于数据存储)等插件。

dependencies:
  flutter:
    sdk: flutter
  chewie: ^1.2.2  # 视频播放
  video_player: ^2.2.10  # 视频播放器核心库
  firebase_auth: ^3.3.3  # 用户认证
  cloud_firestore: ^2.5.4  # 数据库

2. 用户认证

使用Firebase进行用户认证。

import 'package:firebase_auth/firebase_auth.dart';

Future<void> signInAnonymously() async {
  FirebaseAuth auth = FirebaseAuth.instance;
  try {
    UserCredential result = await auth.signInAnonymously();
    User? user = result.user;
    // 处理用户数据
  } catch (e) {
    print(e.toString());
  }
}

3. 视频播放

使用chewievideo_player插件播放视频。

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';

class VideoPlayerScreen extends StatefulWidget {
  final String videoUrl;

  VideoPlayerScreen({required this.videoUrl});

  @override
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late VideoPlayerController _controller;
  ChewieController? _chewieController;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(widget.videoUrl)
      ..initialize().then((_) {
        setState(() {});
      });
    _chewieController = ChewieController(
      videoPlayerController: _controller,
      aspectRatio: _controller.value.aspectRatio,
      autoPlay: false,
      looping: false,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    _chewieController!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: _controller.value.isInitialized
            ? Chewie(controller: _chewieController!)
            : CircularProgressIndicator(),
      ),
    );
  }
}

4. 数据存储与检索

使用Cloud Firestore存储和检索视频信息、评论等。

import 'package:cloud_firestore/cloud_firestore.dart';

// 存储视频信息
Future<void> addVideo(String title, String url) async {
  FirebaseFirestore.instance.collection('videos').add({
    'title': title,
    'url': url,
  });
}

// 获取视频列表
Stream<QuerySnapshot> getVideos() {
  return FirebaseFirestore.instance.collection('videos').orderBy('createdAt').snapshots();
}

// 添加评论
Future<void> addComment(String videoId, String content, String userId) async {
  FirebaseFirestore.instance.collection('videos').doc(videoId).collection('comments').add({
    'content': content,
    'userId': userId,
    'timestamp': FieldValue.serverTimestamp(),
  });
}

5. 使用示例

结合以上功能,你可以创建一个包含视频播放、用户认证和数据存储的完整应用。

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Flutter Douyin-like App')),
        body: FutureBuilder<void>(
          future: signInAnonymously(),  // 用户认证
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return VideoListScreen();  // 视频列表屏幕
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

class VideoListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: getVideos(),  // 获取视频列表
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();
        return ListView.builder(
          itemCount: snapshot.data!.docs.length,
          itemBuilder: (context, index) {
            Map<String, dynamic> video = snapshot.data!.docs[index].data() as Map<String, dynamic>;
            return GestureDetector(
              onTap: () => Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => VideoPlayerScreen(videoUrl: video['url']!)),
              ),
              child: ListTile(
                title: Text(video['title']!),
              ),
            );
          },
        );
      },
    );
  }
}

以上代码提供了一个基本的框架,展示了如何在Flutter应用中集成类似抖音的核心功能。你可以根据需要进一步扩展和定制这些功能。

回到顶部