Balbas Code

DartでのTextFieldの値をLabelに表示

公開日: 2024-07-10 22:31:19

dartでテキストボックスに入れた値を、ボタンを押下したらラベルに入力するコードです。



main.dart


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Text Display Demo'),
);
}
}

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

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
String _text = "";
final TextEditingController _controller = TextEditingController();

@override
void dispose() {
_controller.dispose(); // TextEditingControllerを適切に破棄
super.dispose();
}

void _updateLabel() {
setState(() {
_text = _controller.text; // テキストボックスからテキストを取得して_stateを更新
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title), // アプリバーのタイトル
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'Enter text here', // テキストボックスのラベル
border: OutlineInputBorder(), // テキストボックスの外枠
),
),
const SizedBox(height: 20), // ボタンとテキストボックスの間の余白
ElevatedButton(
onPressed: _updateLabel, // ボタンが押されたときの動作を定義
child: const Text('Display'), // ボタンのテキスト
),
const SizedBox(height: 20), // ラベルとボタンの間の余白
Text(
_text, // 表示されるテキスト
style: Theme.of(context).textTheme.headlineMedium, // テキストのスタイル
),
],
),
),
);
}
}


実行結果
textField_Label1textField_Label2