본문 바로가기
개발/플러터

[플러터] Appbar 에 뒤로가기 버튼 만들기

by 핸디(Handy) 2020. 5. 2.

AppBar 는 앱의 상단에 있는 바입니다. 앱바가 있기 때문에 사용자는 현재 화면의 진행사항을 직관적으로 파악하고 뒤로가기 버튼등을 사용할 수 있습니다.

import 'package:flutter/material.dart';

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

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyFirstWidget(),
    );
  }
}

final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

void openPage(BuildContext context) {
  Navigator.push(context, MaterialPageRoute(
    builder: (BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Second page'),
        ),
        body: const Center(
          child: Text(
            'This is the Second page',
            style: TextStyle(fontSize: 24),
          ),
        ),
      );
    },
  ));
}

/// This is the stateless widget that the main application instantiates.
class MyFirstWidget extends StatelessWidget {
  MyFirstWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        title: const Text('AppBar Example'),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.navigate_next),
            tooltip: 'Next page',
            onPressed: () {
              openPage(context);
            },
          ),
        ],
      ),
      body: const Center(
        child: Text(
          'This is my first page',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

 

Appbar 에 대해 예제코드입니다. 간단히 설명해보도록 하겠습니다.

Appbar에는 여러가지 정보가 들어갈 수가 있습니다. 대표적으로 이미지버튼을 이용한 이벤트입니다.

여기에는 text, iconbutton이 하위 위젯으로 들어가 있습니다.

IconButton이 있고 하위로 icon,tooltip,onPressed 가 들어가있네요.
    icon 은 그대로 넣고자 하는 이미지
    tooltip 은 길게 눌렀을때 뜨는 텍스트
    onPressed 는 눌렸을때 발생하는 이벤트입니다. 여기서는 openPage를 실행하네요.

void onPressed 함수를 보겠습니다.
    일단 첫번째로 Navigator.push 가 보입니다. 네비게이터는 앱에 길을 알려주는 것이라 생각하시면 됩니다. 지금 화면에서 이어지는 다음 화면을 넣어주겠다. 라는 의미에요. 따라서 해당 코드를 넣어주었기 때문에 next page로 가더라도 상단 앱바에 뒤로가기 버튼이 자동으로 생성되는 겁니다.

이것으로 Appbar와 iconbutton를 이용한 페이지 넘기기, 뒤로가기 버튼 생성에 대해 알아보았습니다.


<Custom Appbar>

backgroundColor -> 말그래도 앱바의 배경화면색
TextStyle -> 앱바에 들어가는 텍스트에 대한 스타일설정입니다. 색,크기 등을 지정할 수 있음
centerTitle ->  텍스트를 가운데에 위치할건지에 대한 설정

댓글