You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中的??运算符是什么含义?Flutter SharedPreferences示例解析

What does the ?? operator do in Dart/Flutter?

Hey there! Let me walk you through what that ?? operator is doing in your SharedPreferences code—it's a handy tool for handling null values in Dart.

First off, the ?? is called the null coalescing operator. Its job is straightforward:

  • If the expression on the left side is not null, it uses that value
  • If the left side is null, it falls back to the right side value as a default

Let's break down your specific line of code:

int counter = (prefs.getInt('counter') ?? 0) + 1;

Here's what's happening step by step:

  1. prefs.getInt('counter') tries to fetch an integer value stored under the key 'counter' in SharedPreferences.
  2. If this key hasn't been saved before, or if the stored value isn't an integer, this method will return null.
  3. The ?? 0 kicks in here: if the result from getInt is null, it replaces it with 0; if it's a valid integer (like 5, for example), it keeps that number.
  4. Finally, we add 1 to that value to get our new counter number.

To make it even clearer, here are two scenarios:

  • Scenario 1: prefs.getInt('counter') returns 3 → the expression becomes 3 + 1, so counter = 4
  • Scenario 2: prefs.getInt('counter') returns null → the expression becomes 0 + 1, so counter = 1

This operator is super useful for avoiding null-related errors (like trying to add 1 to a null value) and keeping your code concise instead of writing longer if-else checks for nulls.

内容的提问来源于stack exchange,提问作者Blasanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:50:09