Flutter/내비게이션

routes를 활용한 내비게이션

꽃피는봄날 2021. 6. 18. 10:14

routes 정의

 

routes에 의한 화면 이동

  • push() 메서드 대신 -> pushName() 메서드를 사용

 

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

// 앱 시작 부분
void main() {
  runApp(MyApp());
}


// 시작 클랙스, 머티리얼 디자인 앱 생성!
class MyApp extends StatelessWidget {
  // StatelessWidget 클래스는 상태를 가지지 않는 위젯을 구성하는 기본 클래스.
  // (상태를 가지지 않는 다는 것은-> 한 번 그려진 후 다시 그리지 않는 경우이며,
  // 프로퍼티로 변수를 가지지 않는다 다만 상수는 가질 수 있다.)

  // StatelessWidget 은 build() 메서드를 가지고 있고 이 메서드는 위젯을 생성할 때 호출 되면서 화면에 그릴 위젯을
  // 반환한다.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // title, theme, home 인수를 설정한다. (위젯의 속성을 표현)
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),

      // ↱실행될 때 보여지는 것을 설정 (첫 페이지 설정)
      home: FirstPage(),

      routes: {
        // '/first'는 FirstPage 클래스로, '/second'는 SecondPage클래스로 연결
        '/first':(context) => FirstPage(),
        '/second': (context) => SecondPage(person1: null)
      },
    );
  }
}

// 시작 클래스가 실제로 표시하는 클래스
// 첫 번째 페이지
class FirstPage extends StatelessWidget {
  const FirstPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("첫번째 페이지"),
      ),

      body: ElevatedButton(
        child: Text('다음 페이지로~'),
        onPressed: () async {
          final person = Person("홍길동", 20);

          final result = await Navigator.pushNamed(
            context, '/second'); // Navigator.pushName 끝

          print("돌려받은 데이터-> $result");
        },
      ),
    );
  }
}


// 두 번째 페이지
class SecondPage extends StatelessWidget {
  final Person person1;

  // pesrson1 이름으로 person을 받아서 위에 변수에 넣어줌
  SecondPage({@required this.person1});
  // const SecondPage({Key key, this.person1}) : super(key:key);  // 이렇게도 가능

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("두 번째 페이지!"),
      ),

      body: ElevatedButton(
        child: Text('이전 페이지로'),
        onPressed: (){
          Navigator.pop(context, person1.name);  // 현재 화면을 종료하고 이전 화면으로 이동
        },
      ),
    );
  }
}


class Person{
  String name;
  int age;

  Person(this.name, this.age);

}