[英]Dart Singleton with parameters (global app logger)
I'd like to use the Logger library in my app.我想在我的应用程序中使用Logger库。 I only want to instasiate it once so that I have consistent formatting across my app, instead of passing PrettyPrinter in each file I use it.我只想将它实例化一次,以便在我的应用程序中具有一致的格式,而不是在我使用它的每个文件中传递 PrettyPrinter。 What is the right way of doing this?这样做的正确方法是什么? Should I just use a global const?我应该只使用全局常量吗? Is there a way to do this using a Singleton?有没有办法使用 Singleton 做到这一点?
I define a helper function to get the Logger:我定义了一个助手 function 来获取 Logger:
import 'package:logger/logger.dart';
import 'log_printer.dart';
Logger getLogger(String className) {
return Logger(printer: SimpleLogPrinter(className));
}
Then in each class where I want logging for eaxmple:然后在每个 class 中,我想记录 eaxmple:
class ProfileService with ChangeNotifier {
static final _log = getLogger('ProfileService');
Future<Profile> updateProfile(Profile profile) async {
_log.v('updateProfile');
...
}
...
}
Another example:另一个例子:
class AuthScreen extends StatelessWidget {
final log = getLogger('AuthScreen');
@override
Widget build(BuildContext context) {
log.v('build called');
...
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.