【问题标题】:SharedPref in FlutterFlutter 中的 SharedPref
【发布时间】:2021-12-25 06:30:55
【问题描述】:

我还是比较陌生,我正在尝试从 sharedPref 中获取一个值并仅在它为 false 时才加载我的小部件。但是,当我单步执行代码时,似乎没有点击返回,但是正在渲染小部件。知道如何解决这个问题吗?

Future<bool> getSharedPref() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  if(prefs.getString("abc") == "xyz") {
    return true;
  }
  return false;
}

buildFab() {
  bool isShared = false;
  getSharedPref().then((value) => isShared = value);

  return isShared ? Container(height: 45) : Container(
    height: 45.0,
    width: 45.0,
    child: FabContainer(
      icon: Feather.plus,
      mini: true,
    ),
  );
}

【问题讨论】:

    标签: flutter sharedpreferences


    【解决方案1】:

    用这个替换 buildFab 方法

    buildFab() {
     bool isShared = true;
      setState((){
       isShared = getSharedPref();
        });
    
     return isShared ? Container(height: 45) : Container(
        height: 45.0,
        width: 45.0,
        child: FabContainer(
          icon: Feather.plus,
          mini: true,
        ),
      );
    }
     
    

    在 buildFab 中将 isShared 初始化为 true

    【讨论】:

    • 对不起,我不关注。我不需要制作 isShared Future 吗?为了做到这一点?
    • 编辑了我的答案。请检查
    • isShared = getSharedPref(); 无效,因为我必须将 isShared 设为 Future 类型
    • 没有。它只会返回一个布尔值。您不必将其标记为未来。你试过代码了吗?
    • 是的,如果类扩展状态,而不是无状态,这有关系吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多