序章

share プラグインを使用すると、ネイティブプラットフォームの共有ダイアログを使用してコンテンツを共有する機能をユーザーに提供できます。

この記事では、ワニのリストを含むサンプルのFlutterアプリを作成し、ワニを他のユーザーと共有する機能を追加します。

前提条件

このチュートリアルを完了するには、次のものが必要です。

  • Flutterをダウンロードしてインストールするには。
  • Android StudioまたはVisual StudioCodeをダウンロードしてインストールするには。
  • コードエディタ用のプラグインをインストールすることをお勧めします。 AndroidStudio用にインストールされたFlutterおよびDartプラグイン。 VisualStudioCode用にインストールされたFlutter拡張機能。

このチュートリアルは、Flutter v2.0.6、Android SDK v31.0.2、およびAndroidStudiov4.1で検証されました。

ステップ1—プロジェクトの設定

Flutter用に環境を設定したら、次のコマンドを実行して新しいアプリケーションを作成できます。

  1. flutter create flutter_share_example

新しいプロジェクトディレクトリに移動します。

  1. cd flutter create flutter_share_example<^>

flutter createを使用すると、ボタンがクリックされた回数を表示するデモアプリケーションが作成されます。

ステップ2—shareプラグインを追加する

コードエディタでpubspec.yamlを開き、次のプラグインを追加します。

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter

  share: 2.0.1

次に、変更をファイルに保存します。

ステップ3—プロジェクトの足場

次に、main.dartファイルを更新して、home_page.dartにあるHomePageを含めることができます。

lib / main.dart
import 'package:flutter/material.dart';
import 'home_page.dart';

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

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

新しいhome_page.dartファイルを作成し、コードエディタで開きます。 次のコード行を追加します。

lib / home_page.dart
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My favourite Alligators'),
      ),
      body: Container(),
    );
  }
}

MyHomePageは、AppBarと空のContainerを含むStatefulWidgetになります。

次に、ファイルへの変更を保存します。

ステップ4—サンプルクラスの作成

次に、namedescriptionを含むAlligatorクラスが必要になります。これを使用して、ワニのリストを生成します。

新しいalligator_model.dartファイルを作成し、コードエディタで開きます。 次のコード行を追加します。

lib / alligator_model.dart
import 'package:flutter/foundation.dart';

class Alligator {
  String name;
  String description;

  Alligator({ this.name,  this.description});
}

次に、MyHomePage内にList<Alligator>を作成し、それらを画面に表示できます。

lib / home_page.dart
import 'package:flutter/material.dart';
import 'alligator_model.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Alligator> alligators = [
    Alligator(
      name: 'Crunchy',
      description: 'A fierce Alligator with many teeth.',
    ),
    Alligator(
      name: 'Munchy',
      description: 'Has a big belly, eats a lot.',
    ),
    Alligator(
      name: 'Grunchy',
      description: 'Scaly Alligator that looks menacing.',
    ),
  ];

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My favourite Alligators'),
      ),
      body: Column(
        children: alligators
          .map((Alligator alligator) => Card(
            child: Column(
              children: <Widget>[
                ListTile(
                  title: Text(alligator.name),
                  subtitle: Text(alligator.description),
                ),
              ],
            ),
          ))
          .toList()
      ),
    );
  }
}

ListmapListの内容に追加します。

ステップ5—共有機能を追加する

ユーザーがListTileをクリックするたびに、onTap機能に接続して、share関数を呼び出すようにするために次のようにします。

lib / home_page.dart
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'alligator_model.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Alligator> alligators = [
    Alligator(
      name: 'Crunchy',
      description: 'A fierce Alligator with many teeth.',
    ),
    Alligator(
      name: 'Munchy',
      description: 'Has a big belly, eats a lot.',
    ),
    Alligator(
      name: 'Grunchy',
      description: 'Scaly Alligator that looks menacing.',
    ),
  ];

  share(BuildContext context, Alligator alligator) {
    final RenderBox box = context.findRenderObject();

    Share.share("${alligator.name} - ${alligator.description}",
      subject: alligator.description,
      sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My favourite Alligators'),
      ),
      body: Column(
        children: alligators
          .map((Alligator alligator) => Card(
            child: Column(
              children: <Widget>[
                ListTile(
                  title: Text(alligator.name),
                  subtitle: Text(alligator.description),
                  onTap: () => share(context, alligator),
                ),
              ],
            ),
          ))
          .toList()
      ),
    );
  }
}

このコードは、shareをインポートし、shareメソッドを定義し、onTapで呼び出されます。

注: context.findRenderObject()をキャプチャして、iPadデバイスのsharePositionOriginを確実に渡す必要があります。

コードをコンパイルして、エミュレーターで実行します。

Two screenshots. The first screenshot displays the application running on a mobile device and displaying a list of favorite alligators. The second screenshot displays the messaging app running on a mobile device, after tapping on the Crunchy alligator the details have been shared in the messaging app.

この主要部分はShare関数であり、textとオプションのsubjectを提供できます。この関数を使用して、この例のメッセージングアプリにこれを渡します。

結論

この記事では、ワニのリストを含むサンプルのFlutterアプリを作成し、ワニを他のユーザーと共有する機能を追加しました。

Flutterについて詳しく知りたい場合は、Flutterトピックページで演習とプログラミングプロジェクトを確認してください。