[Flutter] 채팅화면

merci·2023년 4월 2일
0

Flutter

목록 보기
11/24
post-thumbnail

간단하게 채팅화면을 만들면

TextEditingController

class ChatRoomScreen extends StatefulWidget {
  const ChatRoomScreen({Key? key}) : super(key: key);

  
  State<ChatRoomScreen> createState() => _ChatRoomScreenState();

}

class _ChatRoomScreenState extends State<ChatRoomScreen> {
  final List<MyChat> chats = []; // 내가 입력한 채팅 // 상대방 채팅을 저장할 리스트도 필요하긴 함
  final TextEditingController _textEditingController = TextEditingController();
  // 잠깐 잘랐음

여기서 TextEditingController이 사용되었는데 Text 위젯의 텍스트를 편집하는 컨트롤러 역할을 한다.
TextEditingController.text 같은 메소드를 이용해서 텍스트 필드의 값을 가져오거나 수정도 가능하다.

  
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue[100],
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          title: Text("홍길동", style: Theme.of(context).textTheme.headline6,), 
          actions: [ 
            Icon(FontAwesomeIcons.search, size: 20,),
            SizedBox(width: 25,),
            Icon(FontAwesomeIcons.bars ,size: 20,),
            SizedBox(width: 25,)
          ],
        ),
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                  child: Column(
                    children: [
                      TimeLine(time: "2023년 1월 1일 금요일"),
                      OtherChat(
                        name: "홍길동",
                        text: "새해 복 많이 받으세요",
                        time: "오전 10:10",),
                      MyChat(
                        time: "오후 2:15",
                        text: "선생님도 많이 받으십시오.",
                      ),
                      ...List.generate(chats.length, (index) => chats[index]),
                    ],
                  )),
            ),  // Expanded 가 영역을 최대한 확장한다. // 잠깐 잘랐음

Expanded를 이용해서 위아래의 크기를 제외한 가운데 부분의 모든 영역을 SingleChildScrollView로 확장한다.
SingleChildScrollView는 칼럼을 스크롤 가능하게 만들어 준다.

           Container(
             height: 60,
             color: Colors.white,
             child: Row(
               children: [
                 ChatIconButton(icon: Icon(FontAwesomeIcons.plusSquare)),
                 Expanded(
                   child: Container(
                     child: TextField( 
                       controller: _textEditingController, 
                       maxLines: 1,
                       style: TextStyle(fontSize: 20),
                       decoration: InputDecoration(
                         focusedBorder: InputBorder.none,
                         enabledBorder: InputBorder.none,
                       ),
                       onSubmitted: _handleSubmitted, 
                   )
                   ),
                 ),
                 ChatIconButton(icon: Icon(FontAwesomeIcons.smile)), 
                 ChatIconButton(icon: Icon(FontAwesomeIcons.cog)),
               ]
             ),
           )
         ],
       ),
     ),
   );
 }

TextFieldcontroller로 제어한다.
onSubmitted으로 텍스트롤 전송했을때 작동할 기능을 추가한다. -> _handleSubmitted

void _handleSubmitted(text) {
  _textEditingController.clear(); // 전송하면 텍스트필드를 비워줌
  setState(() {
    chats.add(  // 다시 그리기 위해 리스트에 추가
      MyChat(text: text, time: DateFormat("a k:m").format(new DateTime.now()) 
                                    .replaceAll("AM", "오전")
                                    .replaceAll("PM", "오후"),
      ),
    );
  });
}
}

DateFormat를 이용해서 현재 시간을 int 패키지를 이용해서 포맷한다.

DateFormat("a k:m").format(new DateTime.now())

간단하게 화면만 그렸는데 다음에는 데이터를 주고 받아보자

profile
작은것부터

0개의 댓글