Flutter/Flutter 기본

[Flutter] 화면 전환, 데이터 전달3 (Named Route)

Chafle 2023. 5. 12. 02:41
반응형

NamedRoute를 사용하여

RouteTwoScreen->RouteThreeScreen으로 데이터 전달

 

 

- main.dart에 routes 설정하기

 

routes는 

key: Value 형태인데 Value값에 builder형태로 들어간다. 

 

void main() {
  runApp(
    MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/one': (context) => RouteOneScreen(),
        '/two': (context) => RouteTwoScreen(),
        '/three': (context) => RouteThreeScreen(),
      },
    )
  );
}

 

 

 


 

RouteTwoScreen에서 pushNamed를 통해 main.dart에서 설정한 route의 key값으로 화면 전환, arguments로 데이터 전달

 

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

  @override
  Widget build(BuildContext context) {
  
    return MainLayout(
      title: 'Route Two',
      children: [
        Text(
          'arguments: ${arguments}',
        textAlign: TextAlign.center,
        ),
      
        ElevatedButton(
          onPressed: (){
            Navigator.of(context).pushNamed(
                '/three',
                arguments: 999
            );
          },
          child: Text('Push Named'),
        )
    ],
    );
  }
}

 

 


 

 

RouteThreeScreen에서 ModalRoute.of(context)!.settings.arguments로 데이터 받음

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

  @override
  Widget build(BuildContext context) {
    final argument = ModalRoute.of(context)!.settings.arguments;

    return MainLayout(
        title: 'RouteThree',
        children: [
          Text(
              'argument: ${argument}',
            textAlign: TextAlign.center,

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