Skip to content

Instantly share code, notes, and snippets.

@RipplesCode
Created April 8, 2021 15:21
Show Gist options
  • Save RipplesCode/a97912fb6ef5568ead6b7a2a8760435c to your computer and use it in GitHub Desktop.
Save RipplesCode/a97912fb6ef5568ead6b7a2a8760435c to your computer and use it in GitHub Desktop.
GetXService
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();
},
),
],
),
),
),
);
}
}
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