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:
prefs.getInt('counter')tries to fetch an integer value stored under the key'counter'in SharedPreferences.- If this key hasn't been saved before, or if the stored value isn't an integer, this method will return
null. - The
?? 0kicks in here: if the result fromgetIntisnull, it replaces it with0; if it's a valid integer (like 5, for example), it keeps that number. - Finally, we add 1 to that value to get our new
counternumber.
To make it even clearer, here are two scenarios:
- Scenario 1:
prefs.getInt('counter')returns3→ the expression becomes3 + 1, socounter = 4 - Scenario 2:
prefs.getInt('counter')returnsnull→ the expression becomes0 + 1, socounter = 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
相关产品推荐
相关产品推荐

