Reputation: 12463
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'));
}
}
Upvotes: 1
Views: 77
Reputation: 8239
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
Upvotes: 1
Reputation: 3842
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.
Upvotes: 1