Flutter TextFieldの値を取得したい - ぶやかー

TextFieldの値を取得

TextFieldやTextFormFieldの値はTextEditingControllerかonChangedで取得できる。
TextEditingControllerの場合はButton WidgetのonPressed()などトリガーで取得する。
onChangedの場合は、リアルタイムで取得。入力候補を出す場合なんかに使える。

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: const MyHomePage(title: 'Flutter Rank Beginner'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final val1Controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: [
          Text('top'),
          Row(
            children: [
              Flexible(
                child: TextField(
                  controller: val1Controller,
                ),
              ),
              ElevatedButton(
                child: Text('Button'),
                onPressed: () {
                  String val1 = val1Controller.text;
                  print(val1);
                },
              ),
            ],
          ),
          Text('bottom'),
        ],
      ),
    );
  }
}

onchangeの場合

  Widget build(BuildContext context) {
    String textData;
    ....

            TextField(
              onChanged: (text) {
                textData = textData;
                // 候補を出す処理などは、ここで呼び出す。
              },
            ),
    ....

この記事を書いた人 Wrote this article

kmatsunuma

TOP