英文:
Why SharedPreferences is not initializing in this code?
问题
我只翻译代码部分,不提供其他内容:
我只翻译代码部分,不提供其他内容:
我只翻译代码部分,不提供其他内容:
class NewsApiRepository {
NewsApiRepository() {
initializeSharedPrefs();
}
late SharedPreferences prefs;
void getSavedNews() {
final codedData = prefs.getString(key); //Exception thrown here
}
void initializeSharedPrefs() async {
prefs = await SharedPreferences.getInstance();
}
}
英文:
I was just wondering why in Dart/Flutter my variable pref is not being initialized, I get the Unhandled Exception: LateInitializationError: Field 'prefs' has not been initialized.
exception in the getString()
function. Do someone know why?
Thanks for taking the time of reading my question.
class NewsApiRepository {
NewsApiRepository() {
initializeSharedPrefs();
}
late SharedPreferences prefs;
void getSavedNews() {
final codedData = prefs.getString(key); //Exception thrown here
}
void initializeSharedPrefs() async {
prefs = await SharedPreferences.getInstance();
}
}
答案1
得分: 1
初始化偏好设置需要一些时间。我建议只初始化一次,以避免在每次调用NewsApiRepository()时都调用await SharedPreferences.getInstance()。
以下是一个示例:
- 定义您的类
class NewsApiRepository {
SharedPreferences prefs;
NewsApiRepository._(this.prefs);
static NewsApiRepository? _instance;
static NewsApiRepository getInstance() => _instance!;
static void init(SharedPreferences pref) {
_instance = NewsApiRepository._(pref);
}
void getSavedNews() {
final codedData = prefs.getString(key);
}
}
- 在主方法中调用init
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
NewsApiRepository.init(prefs);
runApp(const MyApp());
}
英文:
It takes time to initialize prefs. I suggest initializing once time only to avoid calling await SharedPreferences.getInstance() every time you call NewsApiRepository().
Here is one example to do that:
- Define your class
class NewsApiRepository {
SharedPreferences prefs;
NewsApiRepository._(this.prefs);
static NewsApiRepository? _instance;
static NewsApiRepository getInstance() => _instance!;
static void init(SharedPreferences pref) {
_instance = NewsApiRepository._(pref);
}
void getSavedNews() {
final codedData = prefs.getString(key);
}
}
- Call init inside main method
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
NewsApiRepository.init(prefs);
runApp(const MyApp());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论