본문 바로가기

Flutter (with 코딩셰프)

[2023.11.27] 플러터(flutter) 순한 맛 강좌 22 | Navigator

<< 소스 코드 >>

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.blue
      ),
      home: MyPage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context2) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to the Second page'),
          onPressed: () {
            // Navigator.push(context, MaterialPageRoute(
            //     builder: (BuildContext context){
            //       return SecondPage();
            //     }
            //     ));
            // )
            
            //화면을 Stack 구조로 관리할 때 사용
            //기존 화면 위에 새로운 화면을 엎을 때. push 함수 사용
            //위에 엎어진 화면을 없앨 때는 pop 함수 사용
            //First page 화면 위에 Second page 화면을 덮음
            Navigator.push(context2,
                MaterialPageRoute(
                    builder: (context) => SecondPage()
                    //builder: (_) => SecondPage()  // _는 사용안하는 경우 사용
                )
            );
          },
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext ctx) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to the First page'),
          onPressed: () {
            //Second page 화면을 없애고, 밑에 덮인 First page 화면을 출력
            Navigator.pop(ctx);
          },
        ),
      ),
    );
  }
}

 

<< 출력 화면 >>