본문 바로가기

Flutter

스낵바(Snack bar) 만들기

// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      //빨간띠 삭제
      debugShowCheckedModeBanner: false,
      title: 'TestApp',
      home: MyPage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Snack Bar'),
        centerTitle: true,
      ),
      body: Builder(builder: (BuildContext ctx){
        return Center(
          child: FlatButton(
            color: Colors.red,
            child: const Text(
              'Show me',
              style: TextStyle(color: Colors.white),
            ),
            onPressed: () {
              //Scaffold.of(context) method : 현재 주어진인 context에서 위로 올라가면서 가장 가까운 Scaffold를 찾아서 반환하라.
              Scaffold.of(ctx).showSnackBar(const SnackBar(
                content: Text('data'),
              ));
            },
          ),
        );
      })
    );
  }
}

// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      //빨간띠 삭제
      debugShowCheckedModeBanner: false,
      title: 'TestApp',
      home: MyPage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const 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: RaisedButton(
        child: Text('Show me'),
        onPressed: (){
          Scaffold.of(context).showSnackBar(SnackBar(content: Text('data')));
        },
      ),
    );
  }
}

'Flutter' 카테고리의 다른 글