[Flutter기초7] Navigation

코덩이·2023년 5월 4일

Flutter기초

목록 보기
7/11
post-thumbnail

여러 화면이 존재할 때 Navigator를 통해 화면을 전환할 수 있다.

🌱단순 이동

🌳RouteOneScreen으로 이동

Navigate to the RouteOneScreen

ElevatedButton(
	onPressed: () {
    	Navigator.of(context).push(
        	MaterialPageRoute(builder: (BuildContext context) => RouteOneScreen(),),
        );
    },
	child: Text('Push');
),

🌳Pop을 사용하여 뒤로가기

Return to the first screen

ElevatedButton(
	onPressed: () {
    	Navigator.of(context).pop();
    },
	child: Text('Pop');
),

🌳Argument 전달하기

다른 화면으로 값을 전달하는 방법

🌱Named Route

MaterialPageRoute에 복잡한 코드를 작성하기 싫을 때
최 상단의 MaterialApp 에서 routes를 이용해 PageRoute를 설정해둘 수 있다.

MaterialApp(
  title: 'Named Routes Demo',
  // Start the app with the "/" named route. In this case, the app starts
  // on the FirstScreen widget.
  initialRoute: '/',
  routes: {
    // When navigating to the "/" route, build the FirstScreen widget.
    '/': (context) => const FirstScreen(),
    // When navigating to the "/second" route, build the SecondScreen widget.
    '/second': (context) => const SecondScreen(),
  },
)

🌳다른 화면으로 이동하기

Widget과 Route가 준비되면 Navighator.pushNamed() 메서드를 사용하여 화면을 이동한다.

// Within the `FirstScreen` widget
onPressed: () {
  // Navigate to the second screen using a named route.
  Navigator.pushNamed(context, '/second');
}

🌳Named Route에서 Arguments 전달하기

1. 전달해야하는 Arguments 정의

먼저 새 경로에 전달해야 하는 Arguments를 정의한다.
아래 예제에서 title, message 두 데이터를 전달하고자 한다.
두 데이터를 저장하는 클래스를 만든다.

// You can pass any object to the arguments parameter.
// In this example, create a class that contains both
// a customizable title and message.
class ScreenArguments {
  final String title;
  final String message;

  ScreenArguments(this.title, this.message);
}

2. Arguments를 추출하는 Widget 만들기

title과 message를 받아 표시하는 위젯을 만든다.
ScreenArguments 에 접근하려면 ModalRoute.of() 메소드를 사용한다.
ModalRoute.of() 메서드는 Arguments와 함께 현재 경로를 반환한다.

// A Widget that extracts the necessary arguments from
// the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
  const ExtractArgumentsScreen({super.key});

  static const routeName = '/extractArguments';

  
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute
    // settings and cast them as ScreenArguments.
    final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}

3. routes table에 위젯등록

그런 다음 MaterialApp 위젯에 제공된 routes에 항목을 추가한다.
routes는 route의 이름을 기준으로 작성할 위젯을 정의한다.

MaterialApp(
  routes: {
    ExtractArgumentsScreen.routeName: (context) =>
        const ExtractArgumentsScreen(),
  },
)

4. 위젯으로 이동

마지막으로 사용자가 네비게이터를 사용하여 Navigator.pushNamed() 함수가 실행되는 버튼을 누르면 ExtractArgumentsScreen 화면으로 이동한다.
Arguments 속성을 통해 경로에 인수를 제공한다.
ExtractArgumentsScreen은 이러한 Arguments에서 title과 message를 추출한다.

// A button that navigates to a named route.
// The named route extracts the arguments
// by itself.
ElevatedButton(
  onPressed: () {
    // When the user taps the button,
    // navigate to a named route and
    // provide the arguments as an optional
    // parameter.
    Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'This message is extracted in the build method.',
      ),
    );
  },
  child: const Text('Navigate to screen that extracts arguments'),
),

참고 사이트
https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments

🌱Push 메소드들

🌱Pop 메소드들

profile
개발공부중

0개의 댓글