1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutterでシェア機能を持ったアプリを作成する

Posted at

こんな感じのテキストをシェアするアプリを作ります(これはアプリと言っていいのか...?w)

シェアする機能を使うために、share というライブラリを使います。

pubspec.yamlにshareを追加する

# コマンドを実行する
$ flutter pub add share

or

# pubspec.yamlに直接書き込む
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  
  # 追加
  share: ^2.0.4

AppBarのシェアアイコンで共有できるようにする

Share.share()に共有したいテキストを渡します。

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text('Share Sample'),
      actions: [
        // シェアボタン
        IconButton(
          icon: Icon(Icons.share),
          // シェアボタンをクリックしたときに呼ばれる処理
          onPressed: () => _share(),
        ),
      ],
    ),
  );
}

void _share() => Share.share('共有するテキスト');

これでAppBarのシェアアイコンをクリックすると、共有するためのボトムシートが表示されます。

r(Hot reload)またはR(Hot restart)したときに以下のエラーが発生したら、一度アプリを止めてflutter runを実行すれば、エラーが消えると思います。

E/flutter (28335): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: MissingPluginException(No implementation found for method share on channel plugins.flutter.io/share)
E/flutter (28335): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:7)
E/flutter (28335): <asynchronous suspension>

また、シェアするテキストが空だと、エラーが発生します。

'package:share/share.dart': Failed assertion: line 40 pos 12: 'text.isNotEmpty': is not true.

全体のコード

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Share Sample'),
        actions: [
          IconButton(
            icon: Icon(Icons.share),
            onPressed: () => _share(),
          ),
        ],
      ),
    );
  }

  void _share() => Share.share('');
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?