【问题标题】:if(data != null) NOT IS NULL being ignoredif(data != null) NOT IS NULL 被忽略
【发布时间】:2019-12-02 01:52:56
【问题描述】:

我正在学习使用 FLUTTER 在 DART 中编程 但我处于一种我不明白的情况, 我正在使用这个函数来获取 SharedPreferences 数据

Iterable decoded = jsonDecode(data);
List<Item> result = decoded.map((x) => Item.fromJson(x)).toList();

但是如果我尝试发送为 null 将会出错! 所以我把这个如果

if(data != null)

但它甚至是 null 也通过了

我的代码

Future load() async{

    var prefs = await SharedPreferences.getInstance();
    var data = prefs.getString('data');

    // justing for testing
    print(data);

    if(data != null){

      // another test
      print("NOT IS NULL");
      Iterable decoded = jsonDecode(data);
      List<Item> result = decoded.map((x) => Item.fromJson(x)).toList();
      setState(() {
        widget.itens = result;
      });

    }else{
      print("IS NULL");
    }
  }

然后,查看调试日志

Restarted application in 3.464ms.
flutter: [null]
flutter: NOT IS NULL

对不起我的英语不好

【问题讨论】:

  • 尝试获取指定值并再次检查

标签: flutter dart sharedpreferences


【解决方案1】:

注意print(data) 没有打印null;它打印了[null](即带方括号)。

这意味着data 不是 null。它是一个 List,包含一个 null 元素。

【讨论】:

    【解决方案2】:

    包含单个 null 元素的列表。此处数据不为空。 尝试在 sharedPreference 中添加新元素并再次测试。

    【讨论】:

      【解决方案3】:

      试试if(data),因为该值可以是未定义的,在这种情况下,它是一个假值,但不等于空。

      【讨论】:

      • 看起来你的数据是一个数组,其中一个元素为空,但变量并不是真正的空。
      • estava olhando isso agora mesmo ele retorna [null] não null, testei com uma var aleatoria e retorna apenas null quero so ver como vou sair dessa kkkk mas bom ja ajudou muito
      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多