Flutter
[Flutter]GetX를 이용한 화면 전환
baeksm
2022. 2. 28. 13:34
반응형
get | Flutter Package (pub.dev)
get | Flutter Package
Open screens/snackbars/dialogs without context, manage states and inject dependencies easily with GetX.
pub.dev
Flutter Getx 라이브러리를 이용한 화면 전환 및 컨트롤러 전달 방법
Flutter Getx?
1. 고성능의 상태관리
2. 지능형 의존성 주입
3. 빠르고 실용적인 라우팅 기능
페이지 전환 코드의 변화
기본 플러터에서의 화면전환은 Navigator를 이용한다.
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
이를 GetX를 활용한 코드로 바꾸게 되면
Get.to(
() => SecondRoute(),
);
이렇게 간단하게 화면전환을 이용할 수 있다.
사용예시로 간단하게 화면전환과 함께 컨트롤러를 전달하고, 전달한 컨트롤러를 사용하여, 값을 받아서, 기존화면으로 돌아와 입력된 값을 출력하는 코드를 작성해보겠다.
먼저 기존의 MaterialApp을 GetMaterialApp으로 바꿔준다.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
그리고 전달할 컨트롤러를 만들어 주고,
class IdController extends TextEditingController{
}
class PasswordController extends TextEditingController{
}
Get.put을 이용하여 컨트롤러를 전달한다.
Get.put(IdController());
Get.put(PasswordController());
페이지 이동을 위한 버튼을 하나 만들어주고, Get.to를 이용하여 화면을 이동시켜준다.
OutlinedButton(
onPressed: () {
Get.to(
() => const LoginPage(),
);
},
child: const Text(
'Login',
),
),
이동한 페이지에서, Get.find를 활용하여, 컨트롤러를 가져와 사용한다.
final TextEditingController _idController = Get.find<IdController>();
final TextEditingController _passwordController = Get.find<PasswordController>();
Widget _textFieldWidget(String title){
return TextField(
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
hintText: title,
border: const OutlineInputBorder(),
contentPadding: const EdgeInsets.all(8), // Added this
),
controller: title == '아이디'? _idController:_passwordController,
obscureText: title == '아이디'? false : true,
style: const TextStyle(color: Colors.blue),
);
}
결과