为什么SharedPreferences在这段代码中没有初始化?

huangapple go评论63阅读模式
英文:

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()。

以下是一个示例:

  1. 定义您的类
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);
  }

}
  1. 在主方法中调用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:

  1. Define your class
class NewsApiRepository {

  SharedPreferences prefs;

  NewsApiRepository._(this.prefs);

  static NewsApiRepository? _instance;

  static NewsApiRepository getInstance() =&gt; _instance!;

  static void init(SharedPreferences pref) {
    _instance = NewsApiRepository._(pref);
  }

  void getSavedNews() {
    final codedData = prefs.getString(key);
  }

}
  1. Call init inside main method
Future&lt;void&gt; main() async {

  WidgetsFlutterBinding.ensureInitialized();

  SharedPreferences prefs = await SharedPreferences.getInstance();
  NewsApiRepository.init(prefs);

  runApp(const MyApp());
}

huangapple
  • 本文由 发表于 2023年7月14日 09:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76684243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定