inblog logo
|
taker
    플러터

    TextFormField 에서 값 빼오기

    사용자가 입력한 값 이용하는 법
    김인범's avatar
    김인범
    Dec 29, 2024
    TextFormField 에서 값 빼오기
    Contents
    방법값 입력, 출력 확인
    import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: LoginPage(), ); } } class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: PostWriteBody(), ); } } class PostWriteBody extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Column( children: [ Flexible( child: ListView( shrinkWrap: true, children: [ Container( color: Colors.deepPurple[100], height: 400, width: double.infinity, child: Icon(CupertinoIcons.airplane), ), SizedBox(height: 10), TextFormField(), TextFormField(), ], ), ), TextButton( onPressed: () {}, child: Text("글쓰기"), ), ], ), ); } }
    위 코드에서 사용자가 TextFromField 에 값을 입력하면
    그 값을 꺼내올 수 있도록 해보겠습니다.
    notion image

    방법

    FormField에 컨트롤러를 붙여서 값을 빼올 수 있습니다. (옵저버 패턴)
    TextEditingController() 해당 컨트롤러를 붙여주면 됩니다.
    notion image
    final username = TextEditingController();
    final password = TextEditingController();
    2개를 생성해줍니다.
     
    생성한 컨트롤러를 입력값을 빼낼 TextFormField 에 controller 속성에 넣어줍니다.
    TextFormField(controller: username),
    TextFormField(controller: password),
     
    이후 버튼을 누르면 값을 구하여 사용할 수 있도록 함수를 만들어줍니다.
    void fetch(String username, String password) { print("유저네임>>> $username 나왔습니다."); print("패스워드>>> $password 나왔습니다."); }
     

    값 입력, 출력 확인

    notion image
    notion image
    값이 제대로 출력되고 있는 것을 확인할 수 있었습니다.
    Share article

    taker

    RSS·Powered by Inblog