2
1

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] TextFormFieldの値を変えた時にもう一つのTextFormFieldの値も変える方法

Posted at

一つ目のTextFormFieldのonChangedの中で二つ目のTextEditingControllerを呼び出せばOKです。

必要ないものも入ってますが、消すのめんどくさかったので残してます。※ご了承ください。
Screenshot_1662738372.png

TextEditingController te1 = TextEditingController();
TextEditingController te2 = TextEditingController();

TextFormField(
  controller: te1, //ここに初期値
  onChanged: (text) {
    print('First text field: $text');
    var a = int.parse(text);
    var b = 10 - a;
    print("b ${b}");
    te2.text = b.toString();
  },
),
TextFormField(
  controller: te2, //ここに初期値

),

やり方わからずに再描画で値を変わるようにしてたんですが、再描画じゃダメだと言う指摘を受け重い腰を上げて探したけど全然なくて他の作業を行いながら色々考えてこれなら行けんじゃねってやってみたら行けたので、自身の忘備録がメインですが、誰かの参考になれば幸いです。

コピペでやりたい人はこちらをどうぞ。

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {

    TextEditingController te1 = TextEditingController();
    TextEditingController te2 = TextEditingController();

    @override
    void initState() {
      super.initState();
      te1.text = "123"; // <- こんな感じ
    }

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            TextFormField(
              controller: te1, //ここに初期値
              onChanged: (text) {
                print('First text field: $text');
                var a = int.parse(text);
                var b = 10 - a;
                print("b ${b}");
                te2.text = b.toString();
              },
            ),
            TextFormField(
              controller: te2, //ここに初期値

            ),

          ],
        ),
      ),
    );
  }
}
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?