아래 내용이 정리가 안된거 같아서 새로 정리한 블로그입니다.
2022.06.07 - [Flutter/07 State - Getx] - [Flutter] Getx - Binding
GetX 와 Controller를 인스턴스화 하는 2가지 방법.
- GetPage 에서 설정
- Get.to 에서 설정
Getx controller 파일 - getx_simple.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class GetxSimpleController extends GetxController {
int count = 0;
void increment() {
count++;
update();
}
void putNumber(int number) {
count = number;
update();
}
}
binding_sample.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'getx_simple.dart';
class BindingSamplePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('------------- build(BindingSamplePage) -------------');
return Scaffold(
appBar: AppBar(
title: Text('Buinding test page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GetBuilder<GetxSimpleController>(
builder: (controller){
return Text(controller.count.toString(),
style: TextStyle(fontSize: 30),);
}),
ElevatedButton(
child: Text("바인딩 샘플"),
onPressed: () {
Get.find<GetxSimpleController>().increment();
},
),
],
),
),
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'binding_sample.dart';
import 'getx_simple.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp( // MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: _BindingTestPage(),
getPages: [
GetPage(name: '/binding', page: () => BindingSamplePage(),
binding: BindingsBuilder(() {
Get.put(GetxSimpleController()); <=== 여기서 인스턴스화 함>
}),
),
],
);
}
}
// Binding Test main page
class _BindingTestPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('------------ build(_BindingTestPage) ------------');
return Scaffold(
appBar: AppBar(
title: Text('Flutter Binding Test Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// named routing 경우, GetMaterialApp >> getPages 설정 필요
SizedBox(
width: 120,
height: 50,
child: ElevatedButton(
child: Text("바인딩 관리 Get.toNamed"),
onPressed: () {
Get.toNamed('/binding');
},
),
),
Container(height: 40,),
// Get.to 경우
SizedBox(
width: 120,
height: 50,
child: ElevatedButton(
child: Text("바인딩 관리 Get.put"),
onPressed: () {
Get.to(
() => BindingSamplePage(),
binding: BindingsBuilder(() {
Get.put(GetxSimpleController()); <=== 여기서 인스턴스화 함>
}),
);
},
),
),
]
),
),
);
}
}
<Get.toNamed('/binding') - 첫번째 버튼으로 이동한 경우>
[GETX] GOING TO ROUTE /binding
I/flutter ( 8622): ------------- build(BindingSamplePage) -------------
[GETX] Instance "GetxSimpleController" has been created
[GETX] Instance "GetxSimpleController" has been initialized
[GETX] CLOSE TO ROUTE /binding
[GETX] "GetxSimpleController" onDelete() called
[GETX] "GetxSimpleController" deleted from memory
<Get.to() - 두번째 버튼으로 이동한 경우>
[GETX] GOING TO ROUTE /() => BindingSamplePage
I/flutter ( 8622): ------------- build(BindingSamplePage) -------------
[GETX] Instance "GetxSimpleController" has been created
[GETX] Instance "GetxSimpleController" has been initialized
[GETX] CLOSE TO ROUTE /() => BindingSamplePage
[GETX] "GetxSimpleController" onDelete() called
[GETX] "GetxSimpleController" deleted from memory
[기타 스킬] Binding 을 모아서 클래스로 처리하는 방법
- binding_instance.dart 파일 새로 생성
- main.dart 파일 수정
// binding_instance.dart 파일
import 'package:get/get.dart';
import 'getx_simple.dart';
class BindingInstancePages implements Bindings {
@override
void dependencies() {
// TODO: implement dependencies
Get.put(GetxSimpleController());
}
}
// main.dart 파일 수정
// import 'binding_instance.dart'; 추가필요
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp( // MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: _BindingTestPage(),
getPages: [
// GetPage(name: '/binding', page: () => BindingSamplePage(),
// binding: BindingsBuilder(() {
// Get.put(GetxSimpleController());
// }),
// ),
GetPage(name: '/binding', page: () => BindingSamplePage(),
binding: BindingInstancePages(),), <== 이렇게 처리가능 >
],
);
}
}
[기타 스킬] GetView 로 처리하는 경우 있음
- 주의사항) Get.put 으로 injection 하면 싱글 instance 로 생성됨, Put.create 로 하면 매번 새로운 instance 생성됨.
// binding_sample.dart
class BindingSamplePage extends StatelessWidget {}
==>
class BindingSamplePage extends GetView<GetxSimpleController> {}
ElevatedButton(
child: Text("바인딩 샘플"),
onPressed: () {
Get.find<GetxSimpleController>().increment();
},
),
==>
ElevatedButton(
child: Text("바인딩 샘플"),
onPressed: () {
controller.increment(); <== short coding >
},
),
[기타 스킬] 호출되는 페이지/화면에서 컨트롤러를 직접 바인딩하는 방법
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
// 아래처럼 직접 바인딩하는 방법
final MovieController _movieController = Get.put(MovieController());
[기타 스킬] Get.find<> 생략하는 샘플
// getx_simple.dart
class GetxSimpleController extends GetxController {
static GetxSimpleController get to => Get.find(); // 이 부분 추가
// binding_sample.dart
ElevatedButton(
child: Text("바인딩 샘플"),
onPressed: () {
GetxSimpleController.to.increment(); // 이렇게 처리 가능
// Get.find<GetxSimpleController>().increment();
},
),
'Flutter > 00 Legacy' 카테고리의 다른 글
[Flutter] Firebase SHA-1 keytool (0) | 2021.06.21 |
---|---|
[Flutter] Getx with Dependency Injection (0) | 2021.06.06 |
[Flutter] Getx with state management(reactive version) (0) | 2021.06.04 |
[Flutter] Getx with state management(update version) (0) | 2021.06.04 |
[Flutter] Bloc, Stream - setState 을 Provider 로 변경 (0) | 2021.05.04 |