Skip to content

Instantly share code, notes, and snippets.

@RodBr
Last active Dec 4, 2020
Embed
What would you like to do?
Inject Dependencies
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