🥿

share_plusのshareFilesは廃止されていたみたい?

2024/01/19に公開

画像検索アプリを作るろうとした

久しぶりにやってみた画像のAPIを検索するアプリを作ろうとしたが、パッケージのコードを書が古いのかエラーが出て詰まった!

こちらのチュートリアルをやってみた!
https://zenn.dev/flutteruniv/books/flutter-textbook/viewer/search-free-image-2

error log:

例外が発生しました MissingPluginException (MissingPluginException(No implementation found for method getTemporaryDirectory on channel plugins.flutter.io/path_provider))

https://pub.dev/packages/share_plus/changelog
4.5.0のバージョンからは、非推奨なのか!

iOS: Remove usage of deprecated UIApplication.keyWindow in iOS 13+
Add shareXFiles implementations
Deprecate shareFiles* implementations
Enable shareXFiles implementations on Web

翻訳すると
iOS: iOS 13+で非推奨のUIApplication.keyWindowの使用を削除
shareXFilesの実装を追加
shareFiles*の実装を廃止
Web上でshareXFilesの実装を有効にする

新しく推奨されているコードを使えとのことらしい。

Share.shareXFiles([XFile('assets/hello.txt')], text: 'Great picture');

他にも必要なパッケージを追加:
https://pub.dev/packages/dio
https://pub.dev/packages/path_provider

こちらがソースコード:

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

class PixabayPage extends StatefulWidget {
  const PixabayPage({super.key});

  
  State<PixabayPage> createState() => _PixabayPageState();
}

class _PixabayPageState extends State<PixabayPage> {
  // Viewに表示するJSONのデータを格納するリスト
  List hits = [];

  Future<void> fetchImages(String text) async {
    Response response = await Dio().get(
      'https://pixabay.com/api/?key=[自分のAPI KEY]&q=$text&image_type=photo&pretty=true',
    );
    hits = response.data['hits'];
    setState(() {});
  }

  // ページが呼ばれた時に一度だけ実行される
  
  void initState() {
    fetchImages('花');
    super.initState();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TextFormField(
          initialValue: '花',
          decoration: const InputDecoration(
            fillColor: Colors.white,
            filled: true,
          ),
          onFieldSubmitted: (text) {
            fetchImages(text);
          },
        ),
      ),
      body: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
        ),
        itemCount: hits.length, // Listの要素数を数える。今回は画像の数
        itemBuilder: (BuildContext context, int index) {
          Map<String, dynamic> hit = hits[index]; // 画像の情報を取得indexは0から始まる
          return InkWell(
            onTap: () async {
              // 画像データが入っている変数

              Response response = await Dio().get(
                hit['webformatURL'],
                options: Options(responseType: ResponseType.bytes),
              );
              // path_Providerパッケージを使って端末の一時フォルダに画像を保存

              final Directory dir = await getTemporaryDirectory();
              File file = await File('${dir.path}/image.png')
                  .writeAsBytes(response.data);

              Share.shareXFiles([XFile(file.path)], text: 'Great picture');
            },
            child: Stack(
              fit: StackFit.expand,
              children: [
                Image.network(
                  hit['webformatURL'],
                  fit: BoxFit.cover, // 画像を縦横比を保ったまま全体に表示
                ),
                Align(
                    alignment: FractionalOffset.bottomRight,
                    child: Container(
                        color: Colors.white,
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Icon(Icons.thumb_up_alt_outlined, size: 14),
                            Text('${hit['likes']}'),
                          ],
                        ))),
              ],
            ),
          );
        },
      ),
    );
  }
}

main.dartでimportしてビルドする。

main.dart
import 'package:flutter/material.dart';
import 'package:photo_search/view/pixabay.dart';

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

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

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const PixabayPage(),
    );
  }
}

補足情報

Androidでビルドしようとすると、OSのバージョンのエラーなのか厄介なのが出てきた???
謎の赤いエラーはこのコードを追加すると解決できた。
kotlinのエラーなのか???

これを追加する:

// 他の依存関係...
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.8.10"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.10"

実行結果:


まとめ

Flutterに限ったことではないが、パッケージのコードが古くなることは突然ある。エラーが出たら、パッケージがまだ対応しているのか、データ型が違うからダメなのか見極めないといけないですね。

Discussion