📜  Flutter – 分享加库

📅  最后修改于: 2022-05-13 01:54:51.137000             🧑  作者: Mango

Flutter – 分享加库

在Flutter中, share_plus是一个跨平台共享内容的库。在本文中,我们将创建一个简单的应用程序来展示其功能。为此,请按照以下步骤操作 -

  • pubspec.yaml文件中添加依赖
  • main 中导入依赖项。dart文件
  • 使用 StatefulWidget 构建应用程序
  • 创建一个使用库的方法

现在,让我们继续讨论细节。

安装依赖:

打开项目的pubspec.yaml文件,在文件的 dependencies 部分下添加share_plus库。

导入库:

主要。 dart,导入以下库,

Dart
import 'package:share_plus/share_plus.dart';


Dart
void _onShare(BuildContext context) async {
   final box = context.findRenderObject() as RenderBox?;
    
  // subject is optional but it will be used 
  // only when sharing content over email
   await Share.share(text,
       subject: link,
       sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size);
 }


Dart
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  MyAppState createState() => MyAppState();
}
  
class MyAppState extends State {
  String text = '';
  String link = '';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.green,
      debugShowCheckedModeBanner: false,
      title: 'Flutter Share Plus',
      theme: ThemeData(primarySwatch: Colors.green),
      home: Scaffold(
          appBar: AppBar(
            title: const Text('GeeksForGeeks'),
            backgroundColor: Colors.green,
            centerTitle: true,
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextField(
                    decoration: const InputDecoration(
                      labelText: 'Text:',
                      hintText: 'Enter anything to share',
                    ),
                    maxLines: 2,
                    onChanged: (String value) => setState(() {
                      text = value;
                    }),
                  ),
                  TextField(
                    decoration: const InputDecoration(
                      labelText: 'Subject:',
                      hintText: 'Enter subject to share',
                    ),
                    maxLines: 2,
                    onChanged: (String value) => setState(() {
                      link = value;
                    }),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 12.0)),
                  Builder(
                    builder: (BuildContext context) {
                      return ElevatedButton(
                        onPressed:
                            text.isEmpty ? null : () => _onShare(context),
                        child: const Text('Share'),
                      );
                    },
                  ),
                ],
              ),
            ),
          )),
    );
  }
  
  void _onShare(BuildContext context) async {
    final box = context.findRenderObject() as RenderBox?;
    await Share.share(text,
        subject: link,
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size);
  }
}


创建一个方法

我们需要创建一个异步方法 _onShare(),当我们点击分享按钮分享信息时会调用该方法。有两种不同的方法可以共享两种不同的内容:

  1. 使用 Share.shareFiles() 共享文件
  2. 使用 Share.share() 共享内容

在这里,我们共享包含文本的内容。主题属性是可选的,因为它只会在通过电子邮件发送内容时使用。我们设置了将在屏幕上呈现的框位置,以询问 WhatsApp、电子邮件、蓝牙等共享方法。因此,它可以根据设备上可用的许多共享应用程序正确呈现自己。

Dart

void _onShare(BuildContext context) async {
   final box = context.findRenderObject() as RenderBox?;
    
  // subject is optional but it will be used 
  // only when sharing content over email
   await Share.share(text,
       subject: link,
       sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size);
 }

完整源代码:

Dart

import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  MyAppState createState() => MyAppState();
}
  
class MyAppState extends State {
  String text = '';
  String link = '';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.green,
      debugShowCheckedModeBanner: false,
      title: 'Flutter Share Plus',
      theme: ThemeData(primarySwatch: Colors.green),
      home: Scaffold(
          appBar: AppBar(
            title: const Text('GeeksForGeeks'),
            backgroundColor: Colors.green,
            centerTitle: true,
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextField(
                    decoration: const InputDecoration(
                      labelText: 'Text:',
                      hintText: 'Enter anything to share',
                    ),
                    maxLines: 2,
                    onChanged: (String value) => setState(() {
                      text = value;
                    }),
                  ),
                  TextField(
                    decoration: const InputDecoration(
                      labelText: 'Subject:',
                      hintText: 'Enter subject to share',
                    ),
                    maxLines: 2,
                    onChanged: (String value) => setState(() {
                      link = value;
                    }),
                  ),
                  const Padding(padding: EdgeInsets.only(top: 12.0)),
                  Builder(
                    builder: (BuildContext context) {
                      return ElevatedButton(
                        onPressed:
                            text.isEmpty ? null : () => _onShare(context),
                        child: const Text('Share'),
                      );
                    },
                  ),
                ],
              ),
            ),
          )),
    );
  }
  
  void _onShare(BuildContext context) async {
    final box = context.findRenderObject() as RenderBox?;
    await Share.share(text,
        subject: link,
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size);
  }
}

输出: