오늘은 TextField 에 사용자가 text 를 입력하고 버튼을 누르면 해당 텍스트의 내용으로 dialog 를 띄우는 스크린 구현을 해볼 것이다.
지난 시간까지는 Stateless 로 구현을 했었는데 이번엔 Stateful 로 구현을 할 것이다.
( 텍스트 입력하면 그 내용을 화면에 띄워야하므로 - 상태가 존재해야함 )
import 'package:flutter/material.dart';
void main(){
runApp(const MaterialApp(
home: TextFieldScreen(),
));
}
// Stateful
class TextFieldScreen extends StatefulWidget {
const TextFieldScreen({super.key});
State<TextFieldScreen> createState() => _TextFieldScreenState();
}
class _TextFieldScreenState extends State<TextFieldScreen> {
final TextEditingController _controller = TextEditingController();
// ctrl + o : override 단축키
void dispose() {
_controller.dispose();
super.dispose();
}
void _showValue() {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(_controller.text),
);
}
);
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Text Field Example')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Enter something'),
),
ElevatedButton(onPressed: _showValue, child: Text('Show Value')
),
],
),
),
);
}
}