【问题标题】:Update the UI when app is loaded with data from shared preferences当应用程序加载来自共享首选项的数据时更新 UI
【发布时间】:2021-02-16 16:20:15
【问题描述】:

我已经设法使用共享首选项来保存我的数据。加载应用程序后(关闭后), 数据在后台正确加载,但 UI 在启动时没有更新。

在用户点击日期之前,系统会一直显示默认 UI。 除此之外,给定重量的日期的刻度线也不显示。

我不知道该怎么办。 这是问题所在的演示:

UI not updating in accordance with the stored data (shared preferences)

class UserWeight {
  int id;
  final String weight;
  double totalWeight = 0.0;
  final String date;
  String jsonString;
  var listOfWeights = [];

  UserWeight({this.weight, this.date});

  void addWeight(String dt, String wt) {}

  void removeWeight(String dt) {}
  }

  String getWeight(String dt) {
    if (listOfWeights != null) {
      for (var v in listOfWeights) {
        if (v.containsKey('date')) {
          if (v['date'] == dt) {
            return double.parse(v['weight']).toString();
          }
        }
      }
    }
    return kNoWeightText; // If there is no weight for given date
  }

  String serialize() {
    jsonString = jsonEncode(listOfWeights);
    return jsonString;
  }

  read() async {
    final prefs = await SharedPreferences.getInstance();
    // var b = List<Map<String, dynamic>>.from(jsonDecode(jsonString));
    List<dynamic> s = jsonDecode(prefs.getString('listOfWeights') ?? []);
    listOfWeights = s;
    print("====START OF DECODE===");
    print(listOfWeights);
    for (var v in listOfWeights) {
      print(v);
    }
    print("====END OF DECODE===");
  }

  saveData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('listOfWeights', serialize());
  }
}

HomePage() 是在 main.dart 之后加载的第一个东西

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
   // Other variables;
   UserWeight uw = new UserWeight();

   @override
   void initState() {
       uw.read();
   }
   void dispose() {}
   .....
   // this is called by builder:CalendarBuilders() of the TableCalendar() widget.
   Widget _buildEventsMarker(DateTime date, List events) {
    
    // this creates the tick marks... or it is supposed to do so.
    // events parameter is not used
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      width: 25.0,
      height: 25.0,
      child: Center(
        child: Icon(
          uw.getWeight(date.toString()) != kNoWeightText ? Icons.check : null,
          color: Colors.green,
        ),
      ),
    );
  }
}

请提出任何方法,或者如果需要提供程序包,则说明在此代码中将在哪些地方使用它。

谢谢。

【问题讨论】:

  • 你在哪里调用 read() 方法??
  • 在 initState(){}
  • 在那之后你是在做 setState() 吗?
  • 没有。它会在构建错误期间调用 setState()。

标签: flutter dart sharedpreferences


【解决方案1】:

据我了解,这可能有效:

      class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
        // Other variables;
        UserWeight uw = new UserWeight();

        @override
        void initState() {
          getData();
        }

        getData() async{
          await uw.read();
          if(mounted){
            setState(() {});
          }
        }
        Widget _buildEventsMarker(DateTime date, List events) {
          
          // this creates the tick marks... or it is supposed to do so.
          // events parameter is not used
          return AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            width: 25.0,
            height: 25.0,
            child: Center(
              child: Icon(
                uw.getWeight(date.toString()) != kNoWeightText ? Icons.check : 
                                 null,
                color: Colors.green,
              ),
            ),
          );
        }
      }

【讨论】:

  • 启动时不更新 UI,但值在后台加载(使用控制台检查)。
  • 它不会在您启动应用程序后立即加载,加载需要一些时间,因为它是异步的,然后您的 UI 应该会反映更改。
  • 对不起,我照你说的做了,但是 UI 没有更新,没有出现绿色勾号。
  • @DoomLord 你能找到答案吗?我有同样的问题
  • @AtharvSharma 虽然我已经在一定程度上解决了问题并完成了该应用程序。它已经很久没有维护了。无论如何,完整应用程序的代码可以在我的 GitHub 个人资料上找到:link 所以,试着找出不同之处,它已经很久没有动过,所以我帮不了你太多。这是我尝试完全靠自己构建而不依赖教程(课程)视频的第一个应用程序。所以,目前情况非常糟糕。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
相关资源
最近更新 更多