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 1 year has passed since last update.

Flutter_Genで画像を生成する方法

Last updated at Posted at 2021-10-16

Flutterで画像を使ってみたいと思ったそこのあなた!
割と簡単に使えますよ!!

今回は、日本一わかりやすく理解できるように頑張ってみました。

少しでも役に立てれば嬉しいです!!

はじめに

画像を使う際には、

Image.asset('assets/images/~~~~~.png');

 
といったものを打つと思いますが、一文字でも間違えると画像が表示されませんよね。でもWidgetとかはどうでしょうか。。

Text('') //正常!!

Texx('') //違くね??

と打つと、エラーが出ますよね?

Flutterにおいては、補完機能があることでミスらないようにできています。
せっかくなので、画像を載せるときも同じようにミスらないようにしたいですね。

そんな時に使えるものがflutter_genです!!

詳しくは、以下のリンクを紹介します。(そちらの方がわかりやすいかも!!)

さあ、やってみよう!!

1、画像の追加

フォルダーのやり方はおまかせしますが、困ったら同じ管理の仕方でいいと思います。フォルダーは以下の感じです。

フォルダーの構造
  - .idea
  - android
  - assets
     - images
       - ~~~~.png. <-- ここに画像を追加
  - lib
  - test

2、Flutterのターミナルで色々と打ちます。

Brew tap から flutter_gen をインストール (macos, linux)

brew install FlutterGen/tap/fluttergen

build_runnerflutter_genを入れていきます。

dart pub add build_runner --dev

dart pub global activate flutter_gen

コマンドの確認

fluttergen -h

pubspec.yaml の PATH を指定します。

fluttergen -c pubspec.yaml

一度、ターミナルから脱出しまーす。

ここでpubspec.yamlに色々と追加します

pubspec.yaml
flutter:
  uses-material-design: true
  assets:
    - assets/images/

念のために2つのコードが生成されているかを確認してみください。なかったら、普通に入力できますので安心してください。

「~~~」のところにバージョンを入れてあげてください。
何も記入しなかったら、最新のバージョンが入ります。(多分)

flutter_gen_runner:  〜〜〜 
pubspec.yaml
dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.1.4 
  flutter_gen_runner:

とりあえず、ここまでできたら、魔法のコマンドを打ってあげましょう。

flutter packages pub run build_runner build

そうすると、フォルダーの中に以下のものが追加されていると思います!!

フォルダーの構造
  - .idea
  - android
  - assets
  - lib
    - gen
      - assets.gen.dart <- これこれ!!
    - main.dart
  - test

これでこのファイルがあったら、生成完了です!!!
わかりやすいようにいじっていますが、基本は触らないでください!!

assets.gen.dart

/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
///  FlutterGen
/// *****************************************************

// ignore_for_file: directives_ordering

import 'package:flutter/widgets.dart';

class $AssetsImagesGen {
  const $AssetsImagesGen();

  //ここの 「~~~」を使います!!!!
  String get ~~~ => 'assets/images/~~~.png';
}

class Assets {
  Assets._();

  static const $AssetsImagesGen images = $AssetsImagesGen();
}

class AssetGenImage extends AssetImage {
  const AssetGenImage(String assetName) : super(assetName);

  Image image({
    Key? key,
    ImageFrameBuilder? frameBuilder,
    ImageLoadingBuilder? loadingBuilder,
    ImageErrorWidgetBuilder? errorBuilder,
    String? semanticLabel,
    bool excludeFromSemantics = false,
    double? width,
    double? height,
    Color? color,
    BlendMode? colorBlendMode,
    BoxFit? fit,
    AlignmentGeometry alignment = Alignment.center,
    ImageRepeat repeat = ImageRepeat.noRepeat,
    Rect? centerSlice,
    bool matchTextDirection = false,
    bool gaplessPlayback = false,
    bool isAntiAlias = false,
    FilterQuality filterQuality = FilterQuality.low,
  }) {
    return Image(
      key: key,
      image: this,
      frameBuilder: frameBuilder,
      loadingBuilder: loadingBuilder,
      errorBuilder: errorBuilder,
      semanticLabel: semanticLabel,
      excludeFromSemantics: excludeFromSemantics,
      width: width,
      height: height,
      color: color,
      colorBlendMode: colorBlendMode,
      fit: fit,
      alignment: alignment,
      repeat: repeat,
      centerSlice: centerSlice,
      matchTextDirection: matchTextDirection,
      gaplessPlayback: gaplessPlayback,
      isAntiAlias: isAntiAlias,
      filterQuality: filterQuality,
    );
  }

  String get path => assetName;
}

実際に使ってみよう!

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Center(
            //ここ! (assets.gen.dart)の中の「~~~」を入れる!
            child: Assets.images.~~~.image();
          )
        ],
      ),
    );
  }
}


できたでしょうか???

僕は、最近やっとできました笑
まだまだ勉強不足ですね。。。。頑張ります笑

修正があればどしどしお願いします!!まだあまり慣れていないので笑

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?