Navigator

황훈주·2022년 11월 8일
0

처음화면

두번째 화면

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Go to the Second page'),
          onPressed: () {
            // Navigator.push(
            //   context,
            //   MaterialPageRoute(builder: (BuildContext context) {
            //     return SecondPage();
            //   }),
            // );
            Navigator.push(
                context,
                MaterialPageRoute(
                    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: RaisedButton(
          child: Text('Go to the First page'),
          onPressed: () {
            Navigator.pop(ctx);
          },
        ),
      ),
    );
  }
}

route - 앱 페이지 구조
네비게이터 - 스택 구조 push and pop
인수에 를 쓰는 경우 사용 안하겠다는 뜻.
(
) => SecondPage()


라우트, 푸시네임드

main.dart

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Navigator',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      initialRoute: '/',  
      // 플러터는 초기 이름을 /로 지어뒀음
      routes: {
        '/' : (context) => ScreenA(),
        '/b' : (context) => ScreenB(),
        '/c' : (context) => ScreenC(),
      },
    );
  }
}

home: 과 initialRoute:는 같이 사용될수 없음
route의 키는 '/'로 시작해야 함.

screena.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ScreenA'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(
                color: Colors.red,
                child: Text('Go to ScreenB'),
                onPressed: (){
                  Navigator.pushNamed(context, '/b');
                }),
            RaisedButton(
                color: Colors.red,
                child: Text('Go to ScreenC'),
                onPressed: (){
                  Navigator.pushNamed(context, '/c');
                }),
          ],
        ),
      ),
    );
  }
}
profile
끄적끄적

0개의 댓글

관련 채용 정보