최데브는 오늘도 프로그래밍을 한다.

플러터 - 스낵바 만들기 본문

Flutter

플러터 - 스낵바 만들기

최데브 2021. 6. 20. 16:25
반응형
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'test',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Mypage(),
    );
  }
}

class Mypage extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Snack Bar'),
        centerTitle: true,
      ),
      body: Builder(
        builder: (BuildContext ctx){
          return     Center(
            child: RaisedButton(
              child: Text(
                'show me',
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.red,
              onPressed: () {
                Scaffold.of(ctx).showSnackBar(SnackBar(
                  content: Text(
                    'Hellow',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white
                    ),
                  ),
                  backgroundColor: Colors.teal,
                  duration: Duration(microseconds: 1000),
                ));
              },
            ),
          );
        }
      )
    );
  }
}

fㄴㅇㄹㄴㅁㅇ 여기서  중요하게 봐야할 부분은  Mypage 클래스에서 body에서 Builder 를 사용해서 BuildContext를 만들어주고 아래에 onPress 에서 그 context 를 사용한 점이다. 

토스트 메세지의 경우에는 이런식으로 사용하지 않아도 되지만 스낵바는 bulidcontext 가 없으면 어느 위치에서 스낵바를 띄워야할지 위치를 찾을 수 없다. buildcontext는 위젯들의 위치를 기록하는 데이터? 라고 할 수 있는데

안드로이드에서 context 와 비슷한 개념인거 같다. 

context 는 가장 부모 위젯에서 부터 아래로 상속받으며 내려오는데 위 코드 같은 경우는 ctx 로 상위 scafflold 를 찾아간다고 한다. 

 

머리로는 이해가 되는데 글로 적으려니까 아직 정확하게 개념이 잡히질 않는다.

반응형

'Flutter' 카테고리의 다른 글

플러터의 GetX ?  (0) 2023.01.08
플러터의 위젯이란?  (0) 2022.11.06
플러터란?  (0) 2022.11.06
플러터 - 토스트 메세지 만들기  (0) 2021.06.20
Comments