Created
April 8, 2021 15:21
-
-
Save RipplesCode/a97912fb6ef5568ead6b7a2a8760435c to your computer and use it in GitHub Desktop.
GetXService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_getx/service.dart'; | |
import 'package:get/get.dart'; | |
Future<void> main() async { | |
await initServices(); | |
runApp(MyApp()); | |
} | |
Future<void> initServices() async { | |
print('starting services ...'); | |
await Get.putAsync<Service>(() async => await Service()); | |
print('All services started...'); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
// TODO: implement build | |
return GetMaterialApp( | |
title: "GetX Service", | |
home: Scaffold( | |
appBar: AppBar(title: Text("GetX Service")), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: [ | |
RaisedButton( | |
child: Text("Increment"), | |
onPressed: () { | |
Get.find<Service>().incrementCounter(); | |
}, | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:get/get.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
//This class is like a GetxController. | |
// It shares the same lifecycle ( onInit(), onReady(), onClose()). | |
//It just notifies GetX Dependency Injection system, | |
// that this subclass can not be removed from memory. | |
class Service extends GetxService { | |
Future<void> incrementCounter() async { | |
SharedPreferences prefs = await SharedPreferences.getInstance(); | |
int counter = (prefs.getInt('counter') ?? 0) + 1; | |
print('Pressed $counter times.'); | |
await prefs.setInt('counter', counter); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment