1
0

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の使い方を解説

Posted at

Flutterは、モバイルアプリケーション(iOSとAndroidの両方)を開発するためのオープンソースのUIフレームワークで、Dartプログラミング言語を使用します。以下に、Flutterの基本的な使い方をいくつかのコード例を交えて説明します。

ウィジェットの作成と表示

Flutterでは、UI要素はウィジェット(Widgets)として表現されます。以下は、簡単なテキストを表示するFlutterアプリケーションのコード例です。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutterアプリケーション'),
        ),
        body: Center(
          child: Text('こんにちは、Flutter!'),
        ),
      ),
    );
  }
}

このコードでは、MyApp クラスが StatelessWidget を継承し、build メソッドでUIを構築しています。アプリのエントリーポイントとして main 関数で MyApp インスタンスを作成し、runApp 関数を使用して表示します。

ボタンとイベントハンドリング

ボタンを作成し、クリックイベントを処理するコード例です。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  void _showMessage(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('ボタンがクリックされました。'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('ボタンの例'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () => _showMessage(context),
            child: Text('クリックしてください'),
          ),
        ),
      ),
    );
  }
}

このコードでは、ElevatedButton ウィジェットを使用してボタンを作成し、onPressed プロパティにクリック時のコールバック関数を指定しています。

リストビューの作成

リストビューを作成し、リストアイテムを表示するコード例です。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final List<String> items = ["Item 1", "Item 2", "Item 3"];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('リストビューの例'),
        ),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(items[index]),
            );
          },
        ),
      ),
    );
  }
}

このコードでは、ListView.builder を使用してリストビューを作成し、itemBuilder コールバックで各リストアイテムを生成しています。

これらはFlutterの基本的な使い方の一部です。Flutterでは、さまざまなウィジェットと組み合わせて、複雑なモバイルアプリケーションを構築できます。必要に応じてウィジェットやコンポーネントをカスタマイズし、アプリケーションの要件に合わせてデザインできます。

Flutterのお役立ち情報

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?