2021/3/5 : Flutter : Write your first Flutter app on the webの訳パート1

Contents

Write your first Flutter app on the web

Tip: This codelab walks you through writing your first Flutter app on the web. You might prefer to try writing your first Flutter app on mobileNote that if you have downloaded and configured Android and iOS tooling, the completed app just works on all of these devices!

このコードラボは初めてのweb用Flutterアプリの作り方について見ていきます。あなたはモバイル版の方が慣れているかもしれませんね。AndroidおよびiOSツールをダウンロードして構成した場合、完成したアプリはこれらすべてのデバイスで動作することに注意してください。

 

This is a guide to creating your first Flutter web app.

これはあなたの初めてのFlutter webアプリのガイドです。

 

If you are familiar with object-oriented programming, and concepts such as variables, loops, and conditionals, you can complete this tutorial.

オブジェクト指向プログラミング、および変数、ループ、条件分岐などの概念に精通している場合は、このチュートリアルを完了することができます。

 

You don’t need previous experience with Dart, mobile, or web programming.

Dart、モバイル、またはWebプログラミングの経験は必要ありません。

The web app that you'll be building


What you’ll build

You’ll implement a simple web app that displays a sign in screen.

サインイン(ログイン)画面を表示するだけのシンプルなwebアプリを実装していきましょう。

 

The screen contains three text fields: first name, last name, and username.

この画面は三つのテキストフィールドを含んでいます。

first name

last name

username

の三つです。

 

As the user fills out the fields, a progress bar animates along the top of the sign in area.

ユーザーがフィールドに入力すると、サインイン領域の上部のプログレスバーがアニメーション化されます。

 

When all three fields are filled in, the progress bar displays in green along the full width of the sign in area, and the Sign up button becomes enabled.

3つのフィールドすべてに入力すると、プログレスバーがサインイン領域の全幅に沿って緑色で表示され、[Sign up]ボタンが有効になります。

 

Clicking the Sign up button causes a welcome screen to animate in from the bottom of the screen.

[Sign up]ボタンをクリックすると、ウェルカム画面が画面の下からアニメーション表示されます。

 

このコードラボで完成させるアプリの機能をGIFで示しています。


What you’ll learn

  • webで自然に見えるのFlutterアプリの実装の仕方。
  • Flutterアプリの基本的な構造
  • Tweenアニメーションの実装の仕方
  • StatefulWidgetの実装の仕方
  • デバッガでブレイクポイントをセットする方法

What you’ll use

このコードラボをやるために必要な三つのソフトウェア:

  • Flutter SDK
  • Chrome browser
  • テキストエディタまたはIDE(統合開発環境)

For a web-only codelab, we recommend either IntelliJ IDEA or VS Code. Android Studio and Xcode aren’t required. You can also use a text editor, if you prefer.

Webのみのコードラボですから、IntelliJIDEAまたはVSCodeのいずれかをお勧めします。 AndroidStudioとXcodeは必要ありません。お望みなら、テキストエディタを使用することもできます。

 

While developing, run your web app in Chrome so you can debug with Dart DevTools.

開発中は、Chromeでウェブアプリを実行して、DartDevToolsでデバッグできるようにします。


Step 0: Get the starter web app

You’ll start with a simple web app that we provide for you.

まず私たちが提供するシンプルなウェブアプリから始めます。

 

1.Enable web development.

At the command line, perform the following commands to make sure that you have the latest web support and that it’s enabled.

コマンドラインで次のコマンドを実行して、最新のWebサポートがあり、それが有効になっていることを確認します。

 

You only need to run flutter config once to enable Flutter support for web.

WebのFlutterサポートを有効にするには、

flutter config

コマンドを1回実行するだけで済みます。

 

If you see “flutter: command not found”, then make sure that you have installed the Flutter SDK and that it’s in your path.

「flutter:コマンドが見つかりません(“flutter: command not found”)」と表示された場合は、Flutter SDKがインストールされており、パスに含まれていることを確認(正しくpathを通しているかを確認)してください。

 flutter channel stable
 flutter upgrade

 

web開発導入に関して問題が発生した場合は、buildeng a web app with Flutterをご覧ください。


2.Run flutter doctor

The flutter doctor command reports the status of the installation. You should see something like the following:

flutter doctor

コマンドを実行すると必要なものがインストールされているかを報告してくれます。

おそらく下記のようなリポートが出てくることでしょう。

 flutter doctor

[✓] Flutter: is fully installed. (Channel stable, 1.27.0, on macOS 11.2.1 20D74 darwin-x64, locale en)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Ultimate Edition (version 2020.3.2)
[✓] Connected device (3 available)

• No issues found!

It’s okay if the Android toolchain, Android Studio, and the Xcode tools are not installed, since the app is intended for the web only.

アプリはウェブのみを対象としているため、Androidツールチェーン、Android Studio、Xcodeツールがインストールされていなくても問題ありません。

 

If you later want this app to work on mobile, you will need to do additional installation and setup.

後でこのアプリをモバイルで動作させたい場合は、追加のインストールとセットアップを行う必要があります。


3. List the devices.

To ensure that web is installed, list the devices available. You should see something like the following:

Webがインストールされていることを確認するには、使用可能なデバイスをリストします。 次のようなものが表示されます。
(flutter devicesコマンドを実行する。)
flutter devices
1 connected device:

Chrome (web) • chrome • web-javascript • Google Chrome 88.0.4324.150

The Chrome device automatically starts Chrome.

Chromeデバイスが自動的にChromeブラウザを開きます。


4.The starting app is displayed in the following DartPad.

アプリをスタートすると下記のDartPadのように表示されます。

(元のページに埋め込まれているDartPadのサンプルを動かしてみましょう、という意味だと思われる。)


5.Run the example.

Click the Run button to run the example. Note that you can type into the text fields, but the Sign up button is disabled.

[Run]ボタンをクリックして、サンプルを実行します。 テキストフィールドに入力することはできますが、[Sign up]ボタンは無効になっていることに注意してください。


6.copy the code

Click the clipboard icon in the upper right of the code pane to copy the Dart code to your clipboard.

コードペインの右上にあるクリップボードアイコンをクリックして、Dartコードをクリップボードにコピーします。


7,Create a new Flutter project.

From your IDE, editor, or at the command line, create a new Flutter project and name it signin_example.

IDE、エディター、またはコマンドラインから、新しいFlutterプロジェクトを作成し、signin_exampleという名前を付けます。


8.Replace the contents of lib/main.dart with the contents of the clipboard.

lib /main.dartの内容をクリップボードの内容に置き換えます。


Observations

  • The entire code for this example lives in the lib/main.dart file.

このサンプルのコード全体は、lib /main.dartファイルにコピペします。

 

  • If you know Java, the Dart language should feel very familiar.

Javaを知っているなら、Dart言語は非常に馴染み深いはずです。

 

アプリの全てのUIはDartコードで生成されます。詳しい情報は

Introduction to declarative UI.をご覧ください。

 

●The app’s UI adheres Material Design, a visual design language that runs on any device or platform. You can customize the Material Design widgets, but if you prefer something else, Flutter also offers the Cupertino widget library, which implements the current iOS design language.

アプリのUIは、あらゆるデバイスやプラットフォームで実行されるビジュアルデザイン言語であるマテリアルデザインに準拠しています。 マテリアルデザインウィジェットをカスタマイズすることもできますが、他のものが必要な場合は、Flutterは現在のiOSデザイン言語を実装するCupertinoウィジェットライブラリも提供しています。

Or you can create your own custom widget library.

または、独自のカスタムウィジェットライブラリを作成することもできます。

 

  • In Flutter, almost everything is a Widget. Even the app itself is a widget. The app’s UI can be described as a widget tree.

Flutterでは、ほとんどすべてがウィジェット(Widget)です。 アプリ自体もウィジェットです。 アプリのUIはウィジェットツリーとして説明できます。


Step 1: Show the Welcome screen

SignUpFormクラスはStatefulWidgetです。

This simply means that the widget stores information that can change, such as user input, or data from a feed.

これは、ウィジェットが、ユーザー入力やフィードからのデータなど、変更される可能性のある情報を格納(保持)することを意味します。

 

Since widgets themselves are immutable (can’t be modified once created), Flutter stores state information in a companion class, called the State class.

ウィジェット自体は不変(immutable)であるため(一度作成すると変更できません)、Flutterは状態情報をStateクラスと呼ばれるコンパニオンクラス(companion class)に格納します。

companion:仲間、連れ、同行者、

(SignUpFormクラスと_SignUpFormStateクラスはセット、一組なので、そういう意味で相手のクラス、という意味。)

In this lab, all of your edits will be made to the private _SignUpFormState class.

このラボでは、すべての編集がプライベートなクラスである_SignUpFormStateクラスに対して行われます。


Fun fact

The Dart compiler enforces privacy for any identifier prefixed with an underscore. For more information, see the Effective Dart Style Guide.

Dartコンパイラは、アンダースコアが前に付いた識別子にプライバシーを適用します。 詳細については、「効果的なDartスタイルガイド」を参照してください。


First, in your lib/main.dart file, add the following class definition for the WelcomeScreen widget after the SignUpScreen class:

最初にlib/main.dartファイルで、SignUpScreenクラスの後に、下記のようなWelcomeScreenクラスを定義します。

class WelcomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('Welcome!', style: Theme.of(context).textTheme.headline2),
      ),
    );
  }
}

Next, you will enable the button to display the screen and create a method to display it.

次に、画面を表示するボタンを有効にして、ページ遷移用のメソッドを定義します。

1.Locate the build() method for the _SignUpFormState class.

_SignUpFormStateクラスのbuild()メソッドを見つけます。

 

This is the part of the code that builds the SignUp button.

これは、[Sign up]ボタンを作成するコードの一部です。

 

Notice how the button is defined: It’s a TextButton with a blue background, white text that says Sign up and, when pressed, does nothing.

ボタンがどのように定義されているかに注目してください。これはTextButtonで、背景色が青です。文字の色は白で、Sign upと書かれています。現時点では押しても何も起こりません。

 

2.Update the onPressed property.

onPressedプロパティにコールバック関数をセットします。

 

Change the onPressed property to call the (non-existent) method that will display the welcome screen.

onPressedプロパティに(これから定義する)メソッドをセットして、ボタンを押したらwelcomeスクリーンを表示するようにします。

 

Change onPressed: null to the following:

onPressed: null

の箇所を下記のように修正します。

onPressed: _showWelcomeScreen,

3.Add the _showWelcomeScreen method.

_showWelcomeScreenメソッドを定義します。

 

まだ_showWelcomeScreenメソッドを定義していないので、アナライザが「_showWelcomeScreen is not defined」というエラーを出力しています。それを修正するために、build()メソッドの上に、下記のメソッドょ追加します。

void _showWelcomeScreen() {
  Navigator.of(context).pushNamed('/welcome');
}

4.Add the /welcome route.

/welcome

ルートを追加します。

 

Create the connection to show the new screen.

新しい画面(WelcomeScreen)を表示するためのコネクションを作ります。

 

In the build() method for SignUpApp, add the following route below '/':

SignUpAppウィジェットのbuild()メソッド内で、下記のルートを’/’の下に追加します。

'/welcome': (context) => WelcomeScreen(),

 

class SignUpApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/': (context) => SignUpScreen(),
        '/welcome': (context) => WelcomeScreen(), //←ここに追加。
      },
    );
  }
}

 


5.Run the app.

The Sign up button should now be enabled.

Sign upボタンが有効になりました。ボタンをクリックしてwelcomeスクリーンに行ってみましょう。

 

Note how it animates in from the bottom. You get that behavior for free.

ページ遷移の仕方に注目してください。無料でこれを実装できますよ。

(ボトムからじゃ無い気がするが。)


Observations

●The _showWelcomeScreen() function is used in the build() method as a callback function.

コールバック関数として(_SignUpFormStateクラスの)build()メソッド内で_showWelcomeScreen()メソッドが使われています。

 

Callback functions are often used in Dart code and, in this case, this means “call this method when the button is pressed”.

Dartのコードではコールバック関数はよく使われます。このケースでは、「ボタンが押されたらこのメソッドを呼び出しなさい」という意味です。

 

●Flutter has only one Navigator object.

Flutterにはただ一つのNavigatorオブジェクトがあります。

 

This widget manages Flutter’s screens (also called routes or pages) inside a stack.

このNavigatorウィジェットはFlutterの画面(ルートやページとも呼ばれる)をスタックの中で管理します。

 

The screen at the top of the stack is the view that is currently displayed.

スタックの中の一番上の画面(screen)が、現在画面に表示されているビューです。

 

Pushing a new screen to this stack switches the display to that new screen.

新しい画面をスタックの中にプッシュすることで、画面表示が新しい画面に切り替わります。

 

This is why the _showWelcomeScreen function pushes the WelcomeScreen onto the Navigator’s stack.

これが_showWelcomeScreen関数がWelcomeScreenをNavigatorのスタックにプッシュする理由です。

 

The user clicks the button and, voila, the welcome screen appears.

ユーザーがボタンをクリックすると、はい、welcomeスクリーンが現れます。

 

Likewise, calling pop() on the Navigator returns to the previous screen.

同様に、Navigatorのpop()メソッドを呼び出すと、一つ前の画面に戻ります。

 

Because Flutter’s navigation is integrated into the browser’s navigation, this happens implicitly when clicking the browser’s back arrow button.

Flutterのナビゲーションはブラウザのナビゲーションに統合されているため、これはブラウザの戻る矢印ボタンをクリックすると暗黙的に発生します。


Step 2: Enable sign in progress tracking

This sign in screen has three fields.

このサインイン画面には三つのテキストフィールドがあります。

 

Next, you will enable the ability to track the user’s progress on filling in the form fields, and update the app’s UI when the form is complete.

次に、フォームフィールドへの入力に関するユーザーの進行状況を追跡し、フォームの入力が完了したらアプリのUIを更新する機能を有効にします。


Note:This example does not validate the accuracy of the user input. That is something you can add later using form validation, if you like.

このサンプルでは、ユーザー入力の正確さを検証していません(バリデーション機能は実装してない)。 これは、必要に応じて、form validationを使用して後で追加できます。


1.

Add a method to update _formProgress. In the _SignUpFormState class, add a new method called _updateFormProgress():

_SignUpFormStateクラスが保持する状態フィールドの一つ、_formProgressを更新するメソッドを追加定義します。_SignUpFormStateクラスに_updateFrormProgress()メソッドを定義します。

void _updateFormProgress() {
  var progress = 0.0;
  var controllers = [
    _firstNameTextController,
    _lastNameTextController,
    _usernameTextController
  ];

  for (var controller in controllers) {
    if (controller.value.text.isNotEmpty) {
      progress += 1 / controllers.length;
    }
  }

  setState(() {
    _formProgress = progress;
  });
}

This method updates the _formProgress field based on the number of non-empty text fields.

このメソッドは、入力済みのテキストフィールドの数に応じて、_formProgressフィールドの値を更新します。


2.Call _updateFormProgress when the form changes.

フォームが変更されたら、_updateFormProgressを呼び出します。

 

In the build() method of the _SignUpFormState class, add a callback to the Form widget’s onChanged argument. Add the code below marked as NEW:

_SignUpFormStateクラスのbuild()メソッド内で、FormウィジェットのonChanged引数にコールバックを追加します。下記のコードの

//NEW

と書かれた箇所を追加しましょう。

...
return Form(
  onChanged: _updateFormProgress,  // NEW
  child: Column(
...

 


3.Update the onPressed property (again).

TextButtonのonPressedプロパティを修正します。

 

In step 1, you modified the onPressed property for the Sign up button to display the welcome screen.

step1で、welcomeスクリーンを表示するためにSign upボタンのonPressedプロパティを修正しました。

 

Now, update that button to display the welcome screen only when the form is completely filled in:

フォームが全て入力された時のみwelcomeスクリーンにページ遷移(移動)するようにonPressedフィールドを修正します。

...
TextButton(
  style: ButtonStyle(
    foregroundColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
      return states.contains(MaterialState.disabled) ? null : Colors.white;
    }),
    backgroundColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
      return states.contains(MaterialState.disabled) ? null : Colors.blue;
    }),
  ),
  onPressed: _formProgress == 1 ? _showWelcomeScreen : null, // UPDATED
  child: Text('Sign up'),
),
...

 


4.Run the app.

アプリを実行します。

 

The Sign up button is initially disabled, but becomes enabled when all three text fields contain (any) text.

Sign upボタンは最初は押せませんが、三つのテキストフィールド全てに何らかのテキストを入力したら有効になります(押せるようになる)。


Observations

●Calling a widget’s setState() method tells Flutter that the widget needs to be updated on screen.

ウィジェットのsetState()メソッドを呼び出すと、ウィジェットを画面上で更新する必要があることがFlutterに通知されます。

 

The framework then disposes of the previous immutable widget (and its children), creates a new one (with its accompanying child widget tree), and renders it to screen.

次に、フレームワークは以前の不変ウィジェット(およびその子)を破棄し、新しいウィジェット(付随する子ウィジェットツリーを含む)を作成して、画面にレンダリングします。

 

For this to work seamlessly, Flutter needs to be fast.

これがシームレスに機能するためには、Flutterが高速である必要があります。

 

The new widget tree must be created and rendered to screen in less than 1/60th of a second to create a smooth visual transition—especially for an animation.

特にアニメーションの場合、スムーズな視覚的遷移を作成するには、新しいウィジェットツリーを作成し、1/60秒未満で画面にレンダリングする必要があります。

 

Luckily Flutter is fast.

幸いなことに、Flutterは高速です。

 

●The progress field is defined as a floating value, and is updated in the _updateFormProgress method.

progressフィールド(_formProgressフィールドのことだと思われる)はfloating value(浮動小数)として宣言されています。そして_formProgressフィールドは_updateFormProgressメソッドで更新されます。

 

When all three fields are filled in, _formProgress is set to 1.0.

三つのテキストフィールドが入力された時、_formProgressは1.0にセットされます。

 

When _formProgress is set to 1.0, the onPressed callback is set to the _showWelcomeScreen method.

_formProgressフィールドに1.0がセットされたら、(TextButtonの)onPressedコールバックは_showWelcomeScreenメソッドが選択されます。

 

Now that its onPressed argument is non-null, the button is enabled.

onPressed引数がnullでなくなるので、ボタンを押せるようになります。

 

Like most Material Design buttons in Flutter, TextButtons are disabled by default if their onPressed and onLongPress callbacks are null.

Flutterのマテリアルデザインのほとんどのボタンと同じように、onPressed、onLongPressコールバックがnullのとき、TextButtonは無効(押せない)になります。

 

●Notice that the _updateFormProgress passes a function to setState(). This is called an anonymous function and has the following syntax:

_updateFormProgressメソッド内でsetStateメソッドが実行され、そのsetStateメソッドの引数に関数が渡されています。これは無名関数(anonymous function)と呼ばれ、下記のシンタックスを持ちます。

methodName(() {...});

↑methodNameという名の関数を実行しており、引数として無名関数がコールバックとして渡されている。

 

onPressed: _formProgress == 1 ? _showWelcomeScreen : null,

This is a Dart conditional assignment and has the syntax:

これはDartのconditional assignmentという構文で、シンタックス(記法)は

condition ? expression1 : expression2

のように書きます。

_formProgress == 1

という式がtrueなら、

_formProgress ==1 ? _showWelcomeScreen : null

が、_showWelcomeScreenを返す、

_formProgress == 1

という式がfalseなら、

_formProgress ==1 ? _showWelcomeScreen : null

がnullを返す。


長いのでページを分けます。

次のページへ>>

参考

https://flutter.dev/docs/get-started/codelab-web

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です