Flutter数据提取插件extractor的使用

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

Flutter数据提取插件extractor的使用



extractor

从视频网站如YouTube、Vimeo等直接提取视频链接。

GitHub repo size GitHub



支持的网站

  • youtube.com
  • dailymotion.com
  • vimeo.com
  • yandex.video
  • facebook.com
  • instagram.com (未来更新)
  • soundcloud.com
  • twitter.com
  • tiktok.com
  • vk.com
  • odnoklassniki.ru
  • bilibili.com
  • hotstar.com
  • openloadmovies.net
  • streamago.com
  • tune.pk
  • viu.com

使用方法

pubspec.yaml文件中添加依赖:

dependencies:
  ...
  extractor: ^0.0.1

android > app > build.gradle文件中将minSdkVersion设置为17

android {   
  defaultConfig {     
    minSdkVersion 17      
  }                   
} 

获取直接链接:

void getData() async {
  VideoData results = await Extractor.getDirectLink(link: 'https://www.youtube.com/watch?v=Ne7y9_AbBsY');
}

VideoData 类包含以下字段:

bool? status;
String? message;
String? title;
String? thumbnail;
String? duration;
List<Link>? links;

示例代码

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Direct Link Extractor',
      theme: ThemeData(primarySwatch: Colors.blueGrey),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TextEditingController _urlController = TextEditingController();
  final GlobalKey<ScaffoldState> _key = GlobalKey<ScaffoldState>();
  VideoData? data;
  bool _isLoading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      key: _key,
      appBar: AppBar(
        title: const Text('Direct Link Extractor'),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            margin: const EdgeInsets.all(10),
            child: TextField(
              controller: _urlController,
              decoration: InputDecoration(
                  hintText: '输入网址',
                  isDense: true,
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(15)),
                  suffixIcon: IconButton(
                      onPressed: _handleDirectLink,
                      icon: const Icon(Icons.search))),
            ),
          ),
          Expanded(
            child: _isLoading
                ? const Center(
              child: CircularProgressIndicator(),
            )
                : ListView(
              shrinkWrap: true,
              children: data?.links
                  ?.map((e) => ListTile(
                leading: CircleAvatar(
                  child: Text(e.videoFormat ?? 'N/A'),
                ),
                title: Text(e.text ?? ''),
                subtitle: Text(e.href ?? '', maxLines: 2),
              ))
                  .toList() ??
                  [
                    const Text(
                      '链接将显示在这里',
                      textAlign: TextAlign.center,
                    )
                  ],
            ),
          )
        ],
      ),
    );
  }

  _handleDirectLink() {
    FocusScope.of(context).unfocus();
    if (_urlController.text.isNotEmpty) {
      setState(() {
        _isLoading = true;
      });
      Extractor.getDirectLink(link: _urlController.text).then((value) {
        if (value?.status ?? false) {
          data = value;
          _isLoading = false;
          setState(() {});
        } else {
          setState(() => _isLoading = false);
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text(value!.message!)));
        }
      });
    } else {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('请输入网址')));
    }
  }

  [@override](/user/override)
  void dispose() {
    _urlController.dispose();
    super.dispose();
  }
}

更多关于Flutter数据提取插件extractor的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据提取插件extractor的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用数据提取插件extractor的示例。extractor插件的具体功能和API可能会根据插件的版本和具体实现有所不同,但以下示例将展示如何在一个基本的Flutter应用中集成并使用一个假设的extractor插件进行数据提取。

首先,确保你已经添加了extractor插件到你的pubspec.yaml文件中。由于extractor可能是一个虚构的插件名称,这里我们假设它存在,并且其包名是extractor_plugin

dependencies:
  flutter:
    sdk: flutter
  extractor_plugin: ^1.0.0  # 假设版本号

然后,运行flutter pub get来安装依赖。

接下来,我们将创建一个简单的Flutter应用,展示如何使用这个插件进行数据提取。

1. 初始化Flutter项目

flutter create my_app
cd my_app

2. 更新pubspec.yaml(如上文所示)

3. 使用插件

打开lib/main.dart文件,并更新如下:

import 'package:flutter/material.dart';
import 'package:extractor_plugin/extractor_plugin.dart'; // 引入插件

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String extractedData = '';

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

  Future<void> _extractData() async {
    try {
      // 假设extractData是一个从插件提供的函数,用于提取数据
      String data = await ExtractorPlugin.extractData();
      setState(() {
        extractedData = data;
      });
    } catch (e) {
      print('Error extracting data: $e');
      setState(() {
        extractedData = 'Error extracting data';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Data Extractor Example'),
      ),
      body: Center(
        child: Text(extractedData),
      ),
    );
  }
}

4. 插件方法实现(假设插件源代码)

在实际使用中,ExtractorPlugin插件的源代码将由插件开发者提供。这里是一个简化的插件实现示例,仅用于说明如何编写插件代码(这通常不是Flutter开发者需要做的,除非你自己开发插件)。

iOS 平台(ios/Classes/ExtractorPlugin.swift

import Flutter

public class ExtractorPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: Registrar) {
    let channel = FlutterMethodChannel(name: "extractor_plugin", binaryMessenger: registrar.messenger())
    let instance = ExtractorPlugin()
    instance.setupChannel(channel)
    registrar.addMethodCallDelegate(instance, forChannel: channel.name)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "extractData":
      result("Sample Extracted Data")
    default:
      result(FlutterMethodNotImplemented)
    }
  }

  private func setupChannel(_ channel: FlutterMethodChannel) {
    // 在这里可以添加其他方法
  }
}

Android 平台(android/src/main/kotlin/com/example/extractor_plugin/ExtractorPlugin.kt

package com.example.extractor_plugin

import android.content.Context
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

class ExtractorPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  private var channel: MethodChannel? = null

  override fun onAttachedToEngine(flutterEngine: FlutterEngine, context: Context) {
    channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "extractor_plugin")
    channel?.setMethodCallHandler(this)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    if (call.method == "extractData") {
      result.success("Sample Extracted Data")
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(flutterEngine: FlutterEngine) {
    channel = null
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {}

  override fun onDetachedFromActivityForConfigChanges() {}

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {}

  override fun onDetachedFromActivity() {}
}

注意事项

  1. 插件实际存在性:请注意,extractor_plugin是一个假设的包名,你需要替换为实际存在的插件包名。
  2. 平台特定实现:上面的插件实现代码是简化的,仅用于说明如何编写插件。实际插件可能需要处理更多的逻辑和错误情况。
  3. 插件文档:查阅插件的官方文档以获取更详细的使用说明和API参考。

希望这个示例能帮助你理解如何在Flutter项目中使用数据提取插件。

回到顶部