Flutter网页接收分享意图插件receive_sharing_intent_web的使用

Flutter网页接收分享意图插件receive_sharing_intent_web的使用

receive_sharing_intent_web

receive_sharing_intent_web 是在网页平台上实现 receive_sharing_intent 的一个插件。


限制

目前仅支持通过 Android Chrome PWA 应用程序接收初始媒体内容(getInitialMedia)。


使用方法

要使用此插件,需要在 pubspec.yaml 文件中添加 receive_sharing_intent_webreceive_sharing_intent 作为依赖项。例如:

dependencies:
  receive_sharing_intent: ^1.6.7
  receive_sharing_intent_web: ^0.0.1

网页配置

web/manifest.json 文件中添加以下内容:

{
  ...
  "share_target": {
    "action": "/",
    "method": "GET",
    "params": {
      "title": "title",
      "text": "text",
      "url": "url"
    }
  }
}

完整示例代码

以下是完整的示例代码,展示了如何在网页上使用 receive_sharing_intent_web 插件来接收分享内容。

import 'package:flutter/material.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart'; // 主插件
import 'package:share_plus/share_plus.dart'; // 用于分享功能

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

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

  static const title = 'Receive Sharing Intent Web Example';

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: title,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: title),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  SharedMediaFile? _media; // 用于存储接收到的共享文件信息

  [@override](/user/override)
  void initState() {
    super.initState();
    // 监听初始共享内容
    ReceiveSharingIntent.getInitialMedia().then(_setMediaText);
    // 监听实时共享流
    ReceiveSharingIntent.getMediaStream().listen(_setMediaText);
  }

  void _setMediaText(List<SharedMediaFile> medias) {
    final media = medias.firstOrNull; // 获取第一个共享文件
    if (!mounted || media == null) return;
    setState(() => _media = media); // 更新 UI
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 显示接收到的文本内容
            Text('Text: ${_media?.path}'),
            Text('Type: ${_media?.type.value}'), // 文件类型
            Text('Mime: ${_media?.mimeType}'), // MIME 类型
            const SizedBox(height: 32),

            // 提供输入框用于分享内容
            Form(
              child: TextFormField(
                initialValue: 'https://google.com', // 初始值
                onSaved: (v) => Share.share(v ?? ''), // 分享内容
                decoration: InputDecoration(
                  suffixIcon: Builder(builder: (context) {
                    return IconButton(
                      icon: const Icon(Icons.share), // 分享图标
                      onPressed: () => Form.of(context).save(), // 提交表单
                    );
                  }),
                ),
              ),
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }
}
1 回复

更多关于Flutter网页接收分享意图插件receive_sharing_intent_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


receive_sharing_intent_web 是一个用于在 Flutter Web 应用中接收分享意图(sharing intent)的插件。它允许你的 Flutter Web 应用接收来自其他应用或网页的共享内容,例如文本、链接或文件。

以下是如何在 Flutter Web 项目中使用 receive_sharing_intent_web 插件的步骤:

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 receive_sharing_intent_web 依赖:

dependencies:
  flutter:
    sdk: flutter
  receive_sharing_intent_web: ^1.0.0

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

2. 初始化插件

在你的 main.dart 文件中,初始化 receive_sharing_intent_web 插件。通常,你需要在 main 函数中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化插件
  await ReceiveSharingIntentWeb.initialize();

  runApp(MyApp());
}

3. 监听分享意图

你可以使用 ReceiveSharingIntentWeb 提供的流(Stream)来监听分享意图。通常,你可以在 initState 中开始监听,并在 dispose 中停止监听。

以下是一个简单的示例:

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

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  StreamSubscription? _intentDataStreamSubscription;
  String? _sharedText;

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

    // 监听文本分享意图
    _intentDataStreamSubscription = ReceiveSharingIntentWeb.getTextStream().listen((String value) {
      setState(() {
        _sharedText = value;
      });
    }, onError: (err) {
      print("Error: $err");
    });

    // 获取初始的共享文本
    ReceiveSharingIntentWeb.getInitialText().then((String? value) {
      setState(() {
        _sharedText = value;
      });
    });
  }

  [@override](/user/override)
  void dispose() {
    _intentDataStreamSubscription?.cancel();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Receive Sharing Intent Web'),
        ),
        body: Center(
          child: _sharedText != null
              ? Text('Shared Text: $_sharedText')
              : Text('No shared text received.'),
        ),
      ),
    );
  }
}

4. 处理文件分享

如果你需要处理文件分享,可以使用 getMediaStreamgetInitialMedia 方法来监听和获取共享的文件。

StreamSubscription? _mediaStreamSubscription;
List<SharedMediaFile>? _sharedFiles;

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

  // 监听文件分享意图
  _mediaStreamSubscription = ReceiveSharingIntentWeb.getMediaStream().listen((List<SharedMediaFile> value) {
    setState(() {
      _sharedFiles = value;
    });
  }, onError: (err) {
    print("Error: $err");
  });

  // 获取初始的共享文件
  ReceiveSharingIntentWeb.getInitialMedia().then((List<SharedMediaFile>? value) {
    setState(() {
      _sharedFiles = value;
    });
  });
}

[@override](/user/override)
void dispose() {
  _mediaStreamSubscription?.cancel();
  super.dispose();
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!