英文:
Common class/function called from multiple Widget/State
问题
我有一个函数,被一些小部件或状态类使用。
例如像这样,它检查存储在设备中的常见参数。
我想从多个页面或小部件类中使用这个函数。
对此有什么最佳实践吗?
Future<bool> _getCommonParam() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getBool('param') == null) {
return true;
} else {
return (prefs.getBool('param'));
}
}
英文:
I have a function which is used from a few widget or State class.
For example like this, It checks the common parameters which are stored in device.
I want to use this function from multiple pages or widget class.
What is the best practice for this??
Future<bool> _getCommonParam() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getBool('param') == null){
return true;
}
else {
return (prefs.getBool('param'));
}
}
答案1
得分: 1
你可以将它声明在一个单独的类中,如下所示:
import 'package:shared_preferences/shared_preferences.dart';
class AppPrefs {
static Future<bool> getCommonParam() async {
var prefs = await SharedPreferences.getInstance();
return prefs.getBool('param') ?? true;
}
}
然后,只要导入该类,你就可以从任何地方调用 AppPrefs.getCommonParam()
。
注意:?? 运算符在左侧表达式为 null 时返回右侧表达式。
英文:
You could declare it in a separate class, as such :
import 'package:shared_preferences/shared_preferences.dart';
class AppPrefs {
static Future<bool> getCommonParam() async {
var prefs = await SharedPreferences.getInstance();
return prefs.getBool('param') ?? true;
}
}
You can then call AppPrefs.getCommonParam()
from anywhere as long as you import the class.
Note : The ?? operator returns the right expression if the left expression is null.
答案2
得分: 1
创建具有特定名称和功能的类,并实现与相关类或小部件的方法,就像以下示例一样:
我创建了一个名为AppTheme
的类:
class AppTheme {
static final primaryFontFamily = "CerbriSans";
static Color mainThemeColor() {
return HexColor("#e62129");
}
static TextStyle tabTextStyle() {
return TextStyle(
fontFamily: AppTheme.primaryFontFamily,
fontSize: 14,
fontWeight: FontWeight.normal,
color: AppTheme.mainThemeColor()
);
}
}
然后,我将在另一个类中使用这个类,就像这样:
Text(
"示例",
style: AppTheme.tabTextStyle(),
)
您只需导入与此类相关的库即可。
注意:此示例仅用于理想目的/仅用于概念。
英文:
Create Class with specific name and function and implement methods to related classes or widgets
like below example
I created a class with the name of
class AppTheme {
static final primaryFontFaimly = "CerbriSans";
static Color mainThemeColor() {
return HexColor("#e62129");
}
static TextStyle tabTextStyle() {
return TextStyle(
fontFamily: AppTheme.primaryFontFaimly,
fontSize: 14,
fontWeight: FontWeight.normal,
color: AppTheme.mainThemeColor()
);
}
}
and this class I will use in Another class like this
Text(
"Example",
style: AppTheme.tabTextStyle(),
),
you have to just import library to related this class
Note: This example only for the ideal purpose/only for idea
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论