LoginSignup
9
7

More than 3 years have passed since last update.

Flutterで文字列を入力できるダイアログを作ろう

Last updated at Posted at 2021-02-21

Flutterでダイアログを表示するにはshowDialog()メソッドを用いる。
これを用いて「文字列を入力できるダイアログ」が作りたくなった。
ネットで調べまくったおかげでコードができたので、今回はそれを紹介する。

今回作るもの

aaa.jpg
真ん中のボタンをクリックしたら、
bbb.jpg
こう表示させる(なお、言語設定を省いたので中国語フォントになっています。)

コード

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

void main() => runApp(MaterialApp(
  home: TitleScreen(),
));

class TitleScreen extends StatefulWidget {
  @override
  _TitleScreenState createState() => _TitleScreenState();
}

class _TitleScreenState extends State<TitleScreen> {

  Future<void> InputDialog(BuildContext context) async {    //処理が重い(?)からか、非同期処理にする
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('タイトル'),
            content: TextField(
              decoration: InputDecoration(hintText: "ここに入力"),
            ),
            actions: <Widget>[
              FlatButton(
                color: Colors.white,
                textColor: Colors.blue,
                child: Text('キャンセル'),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                color: Colors.white,
                textColor: Colors.blue,
                child: Text('OK'),
                onPressed: () {
                  //OKを押したあとの処理
                },
              ),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) => Center(
    child: RaisedButton(
      child: Text('ダイヤログを表示'),
      onPressed: () {
        InputDialog(context);
      },
    ),
  );
}

丸々コピペしたら使えます。

AlertDialogのcontentにTextFieldをそのまま指定しているだけなので、実は意外とシンプル。
TextFieldの中身を取得したい場合は、TextEditingControllerで指定してください。

9
7
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
9
7