ネットで見つけたFlutterのコードを素早く動かすための準備方法

※当サイトは、アフィリエイト広告を利用しています

Flutter

How to prepare to test Flutter code found on the internet quickly

ネット上(QiitaとかZennとか)で見つけたサンプルコードを動かしてみたいけど、そのままコピペしてもうまく動かせない

I want to try to run the sample code I found on the web site, but I can't get it to work by copying and pasting it as is.

というときに、試行錯誤の結果、自分が実践している方法を共有したいと思います。
Here is what to do in such cases.

 

本記事は、Flutterを学び始めた初心者の方向けです。Flutter始めたての過去の自分にアドバイスするつもりで書いております。
This article is for beginners who are just starting to learn Flutter, and is intended to give advice to my past self who just started Flutter.

 


40代からプログラミング(Flutter)を始めて、GooglePlayAppStoreにアプリを公開しているhalzo appdevです。

 

作成したアプリはこちら↓ 全てFlutterで開発したアプリです。

 

ネット上で見つけたコードをテストする方法

How to test code found on the Internet.

 

「こんな事できるコード、どこかに落ちてないかな?」
Where can I find the code to make this happen?

と思ってネット上を探すと、日本のサイトではQiitaやZenn、海外のサイトではStackOverflowやGithubのissueページなどに、大変ありがたいサンプルコードがたくさんあります。
If you look for information on the Internet, you can find a lot of very useful sample code on Japanese sites such as Qiita and Zenn, and on foreign sites such as StackOverflow and Github issue pages.

 

これらを見つけたら、まず実際に動くかどうか試してみて、自分自身もそのコードの理解を深めたいですよね。
When you find a sample code that you want, you want to try it out first to see if it actually works, so that you can get a better understanding of the code yourself.

 

方法としては、大きく2つあります。
There are two main ways to do this.

  • Dart Pad上で動かしてみる Try to run it on Dart Pad.
  • 自分の開発環境(Android StudioやVisual Studio Codeなど)で、エミュレーターを使って動かしてみる Try to run it in your own development environment (Android Studio, Visual Studio Code, etc.) using an emulator.

 

Dart Padは、ウェブブラウザ上にエミュレーターも用意されていて、実際の挙動まで試せるので非常に便利です。
Dart Pad is very useful because it provides an emulator on your web browser, and you can try out the actual behavior.

 

ただ、インポートできるパッケージ(あらかじめ色々な機能が実現できるように用意されているコード群)が限られていて、実際には試せないことが多いです。
However, since the types of packages (groups of code prepared in advance to realize various functions) that can be imported are limited, it is often impossible to actually try them out.

 

そのため、ほとんどの場合、後者の方法を使う(自分の開発環境で試す)ことになります。
Therefore, in most cases, you will have to adopt the latter method (i.e., try it in your own development environment).

 

なぜコピペしても動かないか

Why doesn't it work when I copy and paste it?

 

自分の開発環境にコードを貼り付けて、エミュレーターで動かしてみたいのですが、これがそう簡単ではありません。。
I'd like to paste the code into my development environment and try to run it in an emulator, but I can't easily succeed.

 

Flutterのコードは、最初にインポートするパッケージを明記したり、おまじない的なコード(もちろんちゃんと意味はあるのですが、、)をいくつか書く決まりになっています。
Flutter's code starts with the names of the packages to be imported, and some spell-like codes (which of course have their own meanings).

 

ただ、これらのコードを全て書いてブログ記事等に掲載すると、ボリュームが多くなりますし、そもそもエンジニアの方々の間では「あたりまえ」の内容になっているので、そういった「おまじない的な」コードは省略して掲載されることが多いです。
However, if all these codes are written and published in blog posts, etc., the volume will be large. Also, since these spell-like codes are common among engineers, they are often omitted from the articles.

 

そのため、ネット上のサンプルコードをそのまま貼っても「エラーになって動かない」状況になるのですが、これを毎回イチから調整するのがけっこう大変です。
Therefore, even if I paste the sample code from the Internet directly into my development environment, it will not work due to errors. It is also bother to adjust it every time to improve it.

 

できるだけ「おまじない部分」を雛形として準備しておく

Prepare the "spell part" as a template in advance.

 

そこで、ネット上では割愛されている「おまじない部分」をあらかじめ用意しておきます。以下では、開発環境がAndroid Studioの場合の例でご説明します。
So, prepare the "spell-like code" in advance, which is omitted on the internet articles. In the following, as an example, I will explain how I use Android Studio as my development environment.

 

まず、Android Studioで、テスト用のプロジェクトファイルを新しく1つ作成します。
First, in Android Studio, create a new project file for testing.

 

ファイル名は、「my_test_project」など、何でも良いと思います。
The file name can be anything, such as "my_test_project".

 

Flutterのコードは、必ず「main.dart」から実行されるので、次にこの「main.dart」内に最低限のコードを書いておきます。
Flutter's code is always executed from "main.dart", so the next step is to write the minimum code in this "main.dart".

 

デフォルトで記載されているコードは全て削除した上で、以下のコードを貼っておきます。
Delete all the code listed by default, and paste the following code.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      // ↓"Test"は任意の名前で大丈夫です("Test" can be any name you like.)
      title: "Test",

      // ↓このHomeScreenは仮の名前です。ネットから拾ったコードによって後で変更します(This HomeScreen is a temporary name. Change it according to the content of the code you will paste later.)
      home: HomeScreen(),
    );
  }
}

 

これで準備として「おまじない部分」を書いた雛形は完成です。
This completes the template with the "spell part" written as preparation.

 

この雛形を、ネット上のコードをテストするたびに使い回す感じです。
We will use this template every time we test code found on the Internet.

 

もし、ネットから拾ってきたコードの冒頭部分に、

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

といった記述があれば、上記雛形は必要ないので、「main.dart」の中身を丸々、ネット上のコードに置き換えて大丈夫だと思います。
If the first part of the code you picked up from the Internet has the above description, there is no need to use the template you just created. Therefore, you can just replace the entire "main.dart" with the code from the Internet.

 

もし無かった場合には、以下の方法で調整しながら、この雛形にコピペしていきます。
If the code on the Internet does not contain the above description, you can copy and paste it into the template you have just created, adjusting it in the following way.

 

雛形コードを調整した上でコピペする

Adjust the template code and then copy and paste it.

// ↓xxxxxやyyyyyはダミー記述です(xxxxx and yyyyyy are dummy descriptions.)
import 'package:xxxxxxxxx/xxxxxx.dart';
import 'package:yyyyyyyyy/yyyyyy.dart';

class SampleScreen extends StatefulWidget {
  @override
  _SampleScreenState createState() => _SampleScreenState();
}

class _SampleScreenState extends State {
  @override
  Widget build(BuildContext context) {
    return   // 以降、具体的な主となるコード部分が続く・・・(The specific main code section follows...)


  }
}

ネット上で見つけたコードが、上記のようにStateful Widget(状態変化するWidget)から始まっていた場合は、以下の点を調整しながら雛形に貼り付けます。
If the code you find on the Internet starts with a Stateful Widget as shown above, paste it into the template, adjusting the following points.

  1. 雛形にはないimport文を冒頭に追記する Add an import statement at the beginning that is not in the template.
  2. 雛形の「HomeScreen」を、「extends StatefulWidget」の前にあるクラス名(この例では「SampleScreen」)で置き換える Replace "HomeScreen" in the template with the class name in front of "extends StatefulWidget" ("SampleScreen" in this example).
  3. 雛形のMyAppクラスの下に、ネット上のコードを貼り付ける Paste the code found on the Internet under the MyApp class in the template.

 

※調整の仕方は実際のコード内容によって変わる可能性があるので、何卒ご了承ください。
*Please note that the adjustments may vary depending on the actual code content.

 

調整後のコードは以下のような感じです。
The adjusted code looks like the following.

import 'package:flutter/material.dart';

// ↓ネット上のコードにあったimport文を追記(Add the import statement written in the code found on the Internet.)
import 'package:xxxxxxxxx/xxxxxx.dart';
import 'package:yyyyyyyyy/yyyyyy.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Test",

      // ↓このhome:の後をネット上のコードのクラス名に変更(Change the class name after this "home:" to the class name of the code found on the Internet.)
      home: SampleScreen(),
    );
  }
}

// ↓以下に、ネット上のStatefulWidget以下のコードを貼り付ける(Paste the following portion of StatefulWidget from code found on the Internet.)
class SampleScreen extends StatefulWidget {
  @override
  _SampleScreenState createState() => _SampleScreenState();
}

class _SampleScreenState extends State {
  @override
  Widget build(BuildContext context) {
    return   // 以降、具体的な主となるコード部分が続く・・・(The specific main code section follows...)


  }
}

 

ネット上のコードが、以下のようにStateless Widget(状態変化しないWidget)で始まっていた場合も、基本的にはStateful Widgetと同じです。
If the code found on the Internet starts with a Stateless Widget (a Widget whose state does not change) as shown below, it is basically the same as for a Stateful Widget.

import 'package:xxxxxxxxx/xxxxxx.dart';
import 'package:yyyyyyyyy/yyyyyy.dart';

class SampleScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

雛形の「HomeScreen」を、「extends StatelessWidget」の前にあるクラス名(この例でも「SampleScreen」)で置き換える所だけが違いになります。
The only difference is that the "HomeScreen" in the template is replaced by the class name in front of "extends StatelessWidget" (also "SampleScreen" in this example).

 

なお、ネット上のサンプルコードによっては、dartファイルをいくつかに分けているものもあると思いますが、テストする際には、できるだけ全てのコードを同じ「main.dart」内に書いてしまった方が良いと思います。
Some sample codes found on the Internet may be divided by several separate dart files. However, when testing, it is better to write all the code in the same "main.dart" file as much as possible.

 

その理由は、また別の記事で書きたいと思います。
I would like to write about the reasons in another article.

 

pubspec.yamlファイルに必要なパッケージを追記する

Add the necessary packages to the "pubspec.yaml" file.

 

ネット上のコードに、material.dart以外のパッケージがimport文で記載されていた場合には、コードを貼り付けた後に、赤いのニョロニョロマークが出ると思います。
If a package other than "material.dart" is mentioned as the import statement in the code found on the Internet, you will see some red warning marks in the code.

 

これは、まだ必要なパッケージが、プロジェクトファイルにインポートされていないことが原因なので、それに対処します。
This is due to the fact that the necessary packages have not yet been imported into the project file. So, we should resolve that.

 

ブラウザを開いて、pub.devのサイトに行き、検索ボックスにパッケージ名を入れて、該当のパッケージのページを開きます。
Open a browser, go to the pub.dev site, put the package name in the search box, and open the webpage for the corresponding package.

 

パッケージ名は、大体の場合、上のコードの例で言うと「xxxxxx.dart」や「yyyyyy.dart」の「xxxxxx」や「yyyyyy」の部分になります。
The package name is usually the "xxxxxx" or "yyyyyyy" part of "xxxxxx.dart" or "yyyyyyy.dart" in the example code above.

 

パッケージのページを開いたら、「Installing」のタブを開いて、

dependencies:
    xxxxxx: ^1.1.1

のように書かれている「xxxxxx: ^1.1.1」の部分をコピーします(ここでは「1」の部分はダミーの数字です)。
After opening the web page of the package, open the "Installing" tab and copy the "xxxxxx: ^1.1.1" part written as in the example above (the "1" part is a dummy number).

 

Android Studioに戻って、プロジェクトフォルダの直下にある(画面左側のリストの下の方)「pubspec.yaml」ファイルを開き、「dependencies:」のゾーンに、下のように貼り付けます。
Go back to Android Studio, open the "pubspec.yaml" file located directly under the project folder (the bottom one in the list on the left side of the screen), and paste the copied part into the "dependencies:" zone, as shown in the example below.

dependencies:
 ・・・
 ・・・(既に何かか書かれている部分(The part where some codes have already been written.))
 ・・・
   xxxxxx: ^1.1.1   #必ずインデントは左から半角スペース2マス必要な点に注意!(Note that the indent must be two spaces from the left!)
   yyyyyy: ^1.1.1

 

貼り付けたら、画面右上の「Pub get」を押します。
After pasting, press "Pub get" in the upper right corner of the screen.

 

画面下の「0: Messages」のウィンドウ内に「Process finished with exit code 0」と表示されれば、無事、パッケージのインポートが完了です。これで、main.dart内の赤いニョロニョロも消えます。
If you see "Process finished with exit code 0" in the "0: Messages" window at the bottom of the screen, you have successfully imported the package. Now, the red warning marks in "main.dart" will disappear.

 

あとはエミュレーターを起動して、実行すれば、ネット上のサンプルコードを試すことができると思います。
Then, if you start the emulator and run it, you will be able to try the sample code found on the Internet.

 

以上、ご参考になれば幸いです。
I hope the above is helpful.

最後までお読みいただき、ありがとうございました。
Thank you for reading to the end.
 

 

個人アプリ開発で役立ったもの

おすすめの学習教材

超初心者向けでオススメな元Udemyの講座/

 

 \キャンペーン時を狙えば安価で網羅的な内容が学べる(日本語訳あり)/

 

\Gitの基礎について無料で学べる/

 

おすすめの学習書籍

実用的image_pickerに関してかなり助けられた/

 

Dartの基礎文法を素早くインプットできる/


Dart入門 - Dartの要点をつかむためのクイックツアー

コメント

タイトルとURLをコピーしました