본문 바로가기

Flutter (with 코딩셰프)

[2023.11.23] 플러터(flutter) 순한 맛 강좌 19-1 | Snack Bar (without Builder)

<< 소스 코드 >>

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Snack Bar',
      theme: ThemeData(
        primarySwatch: Colors.red
      ),
      home: MyPage(),
    );
  }
}

class MyPage extends StatelessWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Snack Bar'),
        centerTitle: true,
      ),
     body: MySnackBar(),
    );
  }
}

class MySnackBar extends StatelessWidget {
  const MySnackBar({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(  //RaisedButton이 ElevatedButton으로 대체됨.
        child: Text('Show me'),
        onPressed: (){  //버튼 클릭 이벤트 지정
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(
            content: Text('Hellow',   //SnackBar 내용 지정
              textAlign: TextAlign.center,  //문자 정렬
              style: TextStyle( //문자 스타일 지정
                color: Colors.white,  //문자 색상 지정
              ),
            ),
            backgroundColor: Colors.teal, //SnackBar 배경 색 지정
            duration: Duration(milliseconds: 1000), //메세지 전달 시간 지정 (1초)
          ),
          );
        },
      ),
    );
  }
}


 

<< 출력 화면 >>