ABOUT ME

Today
Yesterday
Total
  • Navigator 다루기 push(), pop() 화면 전환
    프로그래밍 공부 메모/flutter 2022. 5. 29. 20:26

    1. 플러터에서 네비게이터는 각 화면의 데이터를 가지고 화면 전환을 담당한다

    2. 네비게이터는 기본적으로 stack 자료구조를 사용하여 화면을 쌓아 올린다

    3. 데이터 추가(화면 이동) - push()  / 데이터 삭제 (화면 끄기) - pop()

     

    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 MaterialApp(
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const MyPage(),
        );
      }
    }
    
    class MyPage extends StatelessWidget {
      const MyPage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          //backgroundColor: Colors.grey,
          appBar: AppBar(
            title: Text('first page'),
          ),
          body: Center(
            child: ElevatedButton(
              child: Text('go to the second page'),
              onPressed: () {
                Navigator.push(
                  context, //context 파라미터는 현재 내가 어디에 있는지 나타내며
                  //MyPage 빌드 위젯의 파라미터 명과 같아야한다
                  MaterialPageRoute(
                    builder: (context) => SecondPage(),
                  ),
                );
              },
            ),
          ),
        );
      }
    }
    
    class SecondPage extends StatelessWidget {
      const SecondPage({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext ctx) {
        return Scaffold(
          //backgroundColor: Colors.grey,
          appBar: AppBar(
            title: Text('second page'),
          ),
          body: Center(
            child: ElevatedButton(
              child: Text('go to the first page'),
              onPressed: () {
                Navigator.pop(ctx); // 자신의 화면을 삭제 , 파라미터 값으로 ctx 자신의 빌드컨텍스트 데이터를 전달
              },
            ),
          ),
        );
      }
    }
    반응형
Designed by Tistory.