0Pricing
Flutter Mobile Development · บทเรียน

Shared Preferences สำหรับข้อมูล

ใช้ `shared_preferences` เพื่อจัดเก็บข้อมูลปริมาณเล็กน้อย เช่น การตั้งค่าและค่ากำหนดของผู้ใช้ในรูปคู่คีย์-ค่าไว้ภายในอุปกรณ์

Shared Preferences สำหรับข้อมูล เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What are Shared Preferences?

When building mobile apps, you often need to store small bits of data locally on the device. This could be anything from a user's dark mode preference to their last logged-in status.

shared_preferences is a Flutter package that helps you do just that! It provides a simple way to store key-value pairs of primitive data types.

Why Use Shared Preferences?

  • Simple Data: Ideal for storing simple data types like booleans, integers, doubles, strings, and lists of strings.
  • User Settings: Perfect for saving user preferences, app settings, or theme choices.
  • Lightweight: It's a quick and easy way to persist small amounts of data without needing a full database.

Think of it like a small digital notepad for your app's temporary memory!

Installing the Package

To use shared_preferences, you first need to add it to your project's dependencies.

Open your pubspec.yaml file and add the following line under dependencies:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.2.2 # Add this line

Saving Your First Preference

Once the package is added, you can start saving data. You'll need to get an instance of SharedPreferences and then use methods like setBool(), setString(), etc.

Remember to use await because these operations are asynchronous!

import 'package:shared_preferences/shared_preferences.dart';

Future<void> saveSetting() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setBool('isDarkMode', true);
  print('Dark mode setting saved!');
}

Run It: Saving a Boolean

Try running this example to see how a boolean value is saved. We'll set a 'welcomeShown' flag to true.

import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); 
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // Save a boolean value
  await prefs.setBool('welcomeShown', true);
  print('welcomeShown saved: ${prefs.getBool('welcomeShown')}');
}

Retrieving Saved Data

To get data back, you use corresponding get methods like getBool(), getString(), etc. These methods return a nullable type (e.g., bool?) because the key might not exist.

It's good practice to provide a default value using the ?? operator if the key is not found.

import 'package:shared_preferences/shared_preferences.dart';

Future<bool> getSetting() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  // Get 'isDarkMode', default to false if not found
  bool isDark = prefs.getBool('isDarkMode') ?? false;
  return isDark;
}

Run It: Loading a Boolean

Let's load the welcomeShown preference we saved earlier. Notice how we handle the case where it might not exist by providing a default of false.

import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // Load 'welcomeShown', default to false if not present
  bool welcomeShown = prefs.getBool('welcomeShown') ?? false;
  print('Is welcome screen already shown? $welcomeShown');

  // Let's try to load a key that doesn't exist
  String? userName = prefs.getString('userName');
  print('User Name: ${userName ?? 'Guest'}');
}

Saving Other Data Types

shared_preferences supports several basic data types:

  • setString(key, value) for text
  • setInt(key, value) for whole numbers
  • setDouble(key, value) for decimal numbers
  • setStringList(key, value) for lists of strings

There are corresponding get methods for each type.

Run It: Saving Mixed Data

This example demonstrates saving and loading a string, an integer, and a list of strings. See how different types are handled.

import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // Save different data types
  await prefs.setString('userName', 'Coddy');
  await prefs.setInt('score', 12345);
  await prefs.setStringList('favoriteFoods', ['Pizza', 'Sushi', 'Tacos']);
  print('All data saved!');

  // Load and print them
  String? name = prefs.getString('userName');
  int? score = prefs.getInt('score');
  List<String>? foods = prefs.getStringList('favoriteFoods');

  print('User Name: ${name ?? 'N/A'}');
  print('Score: ${score ?? 0}');
  print('Favorite Foods: ${foods ?? []}');
}

Deleting Preferences

You can also remove stored preferences:

  • remove(key): Deletes a specific key-value pair.
  • clear(): Deletes ALL data stored by your app using shared_preferences. Use with caution!

Both methods are asynchronous and return a Future<bool> indicating success.

Quick Check

You want to store a user's preferred language, which is a single string like 'en_US' or 'es_ES'. Which shared_preferences method is the most appropriate for saving this data?

Recap & Next Steps

Great job! You've learned how to use shared_preferences to store and retrieve small, simple data locally in your Flutter applications.

  • It's ideal for user settings and preferences.
  • Supports basic types: bool, int, double, string, and List<String>.
  • Operations are asynchronous (use await).
  • Remember to handle null values when retrieving data.

Next, you'll explore more structured data storage with SQLite databases!

คำถามที่พบบ่อย

บทเรียน “Shared Preferences สำหรับข้อมูล” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “Shared Preferences สำหรับข้อมูล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “Shared Preferences สำหรับข้อมูล”

ใช้ `shared_preferences` เพื่อจัดเก็บข้อมูลปริมาณเล็กน้อย เช่น การตั้งค่าและค่ากำหนดของผู้ใช้ในรูปคู่คีย์-ค่าไว้ภายในอุปกรณ์ คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “Shared Preferences สำหรับข้อมูล” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม

ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. Shared Preferences สำหรับข้อมูล
  2. การผสานรวมฐานข้อมูล SQLite
  3. การดำเนินการกับระบบไฟล์
  4. Hive และพื้นที่จัดเก็บภายในแบบ NoSQL
← กลับไปที่ Flutter Mobile Development