我有一个函数,它从几个小部件或状态类中使用。
例如,它检查存储在设备中的公共参数。
我想从多个页面或小部件类中使用此功能。
对此的最佳实践是什么?
Future<bool> _getCommonParam() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.getBool('param') == null){
return true;
}
else {
return (prefs.getBool('param'));
}
}
您可以在单独的类中声明它,如下所示:
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,则 ?? 运算符返回右表达式。
创建具有特定名称和函数的类,并实现相关类或小部件的方法
如下例所示
我创建了一个名为
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()
);
}
}
和这个类我将在另一个这样的类中使用
Text(
"Example",
style: AppTheme.tabTextStyle(),
),
您只需将库导入相关此类
注意:此示例仅用于理想目的/仅用于想法