Last active
November 3, 2022 09:48
-
-
Save RodBr/dc947400f81987511741e39e92531652 to your computer and use it in GitHub Desktop.
Inject Dependencies
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:get/get.dart'; //STEP 1 - import Get | |
void main() { | |
//STEP 3 - add our services - immediate or lazy | |
Get.put(TestService()); | |
Get.lazyPut<AuthService>(() => AuthService()); | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
//STEP 2 - replace MaterialApp with GetMaterialApp | |
return GetMaterialApp( | |
title: 'Flutter Demo', | |
enableLog: false, | |
theme: ThemeData( | |
primaryColor: Colors.purple, | |
buttonColor: Colors.green, | |
textTheme: TextTheme( | |
bodyText2: TextStyle(color: Colors.indigo, fontSize: 20))), | |
home: Testpage(), | |
); | |
} | |
} | |
class Testpage extends StatefulWidget { | |
Testpage({Key key}) : super(key: key); | |
@override | |
_TestpageState createState() => _TestpageState(); | |
} | |
class _TestpageState extends State<Testpage> { | |
//BONUS 2 - clearer code | |
var height = Get.height; | |
var orientation = Get.mediaQuery.orientation; | |
var isDarkMode = Get.isDarkMode; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Inject Dependencies'), | |
centerTitle: true, | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text('Welcome', style: Get.textTheme.headline5), | |
Text('height: ${height.truncate()}'), | |
Text('orientation: $orientation'), | |
Text('dark mode: $isDarkMode'), | |
SizedBox(height: 24), | |
RaisedButton( | |
onPressed: () { | |
// STEP 4 - call the TestService service | |
TestService.to.testStuff(); | |
}, | |
child: Text( | |
'Call Service', | |
style: TextStyle(color: Colors.white), | |
), | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class TestService { | |
static TestService get to => Get.find(); | |
testStuff() { | |
//STEP 4 - call the AuthService | |
String result = Get.find<AuthService>().authStuff(); | |
//BONUS 1 - snackbar without context or builder | |
Get.snackbar('TestService', result, | |
overlayBlur: 4, backgroundColor: Colors.orange); | |
} | |
} | |
class AuthService { | |
authStuff() { | |
//BONUS 1 - interrogate page status without context | |
print(Get.textTheme.headline5.color); | |
print(Get.height); | |
print(Get.mediaQuery.orientation); | |
print(Get.isDarkMode); | |
return 'You are Authorized'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment