Last active
September 27, 2023 18:08
-
-
Save luisfelipeas5/e39b6fee76eb2d2bd7a35b8ba67828d6 to your computer and use it in GitHub Desktop.
GetIt - get null implementation
This file contains hidden or 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
//Possible solution for https://stackoverflow.com/questions/77187279/is-it-possible-to-provide-a-null-implementation-when-registering-something-on-fl/77187634#77187634 | |
import 'package:flutter/foundation.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:get_it/get_it.dart'; | |
class OurOwnInterface {} | |
void main() { | |
if (kDebugMode) { | |
GetIt.I.registerSingleton<OurOwnInterface>(OurOwnInterface()); | |
} | |
runApp(const MainApp()); | |
} | |
class MainApp extends StatelessWidget { | |
const MainApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
OurOwnInterface? appModel = GetIt.I.getOrNull(); | |
return MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: Text('Hello World! ${appModel.runtimeType}'), | |
), | |
), | |
); | |
} | |
} | |
extension GetItExtension on GetIt { | |
T? getOrNull<T extends Object>() { | |
try { | |
return GetIt.I.get<T>(); | |
} on StateError catch (_) { | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment