플랜데버 2021. 3. 4. 16:35

 

입력값 받아오기

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Chat App"),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: _textEditingController,
                decoration: InputDecoration(hintText: "메세지 입력창"),
                onSubmitted: (String text) {  //키보드 확인버튼 탭하면 값 보내준다
                  print("onSubmitted: $text");
                },
              ),
            ),
            FlatButton(
              onPressed: () {
                print(_textEditingController.text);
              },
              child: Text("Send"),
              color: Colors.amber,
            ),
          ],
        ),
      ),
    );
  }
}

 

 

공통 함수로 만들기

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  TextEditingController _textEditingController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Chat App"),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _textEditingController,
                    decoration: InputDecoration(hintText: "메세지 입력창"),
                    onSubmitted: (String text) {     ---> ①
                      _handleSubmitted(text);
                    },
                  ),
                ),
                FlatButton(
                  onPressed: () {
                    _handleSubmitted(_textEditingController.text);
                  },
                  child: Text("Send"),
                  color: Colors.amber,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  //텍스트 입력시 같은기능
  void _handleSubmitted(String text) {
    print(text);
    _textEditingController.clear(); //입력 후 텍스트창 비워준다.

  }
}

①의경우 보내는 형식이 겹쳐서 생략가능하다. 자동으로 string 을 넘겨준다. 아래 처럼 써줘도 된다.

onSubmitted:  _handleSubmitted;