在 Flutter 中,有没有一种方法可以从存储的文件中提取不同的内容和动态列表?

In Flutter, is there a way in which I can draw different contents and dynamic lists from the stored file?

为了解决第一个问题,我目前使用的方法是在异步加载文件时在body中放置一个content变量,加载完成后,调用setState() 并设置 content.

的值
class _MyHomePageState extends State<MyHomePage>{
  dynamic content;
  void setContent(bool? hasRes){
    setState(() {
      if(hasRes!=null&&hasRes){
        content = const ContentWhenHasRes();
      }else{
        content = const ContentWhenNoRes();
      }
    });
  }
  @override
  Widget build(BuildContext context){
    //Load the $hasRes$ var and determine which interface to draw
    SharedPreferences.getInstance().then((pref) => {
      setContent(pref.getBool('hasRes'))
    });
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: content
    );
  }
}

但我不知道这是否有效,是否有更优雅的方法来做到这一点? 此外,我发现从本地存储加载列表以显示在 ListView 中存在问题。我知道使用 `ListView.builder' 但是,我的问题仍然是 i/o 部分。

SharedPreferences.getInstance().then((pref) => {
  setContent(pref.getBool('hasRes'))
});

这些代码不应该放在build()方法中,因为build()方法被频繁执行,而是将io代码放在initState()中。

另一种方法是 setState() hasRes 变量:

class _MyHomePageState extends State<MyHomePage>{
  bool _hasRes = false;

  @override
  void initState() {
    super.initState();
    //Do this in initState()
    SharedPreferences.getInstance().then((pref) => {
      _hasRes = pref.getBool('hasRes');
      setState((){});
    });
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _hasRes ? ContentWhenHasRes() : ContentWhenNoRes(),
    );
  }
}