欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flutter本地存儲(chǔ)之基本的鍵值對(duì)存儲(chǔ)詳解

 更新時(shí)間:2023年03月21日 08:19:46   作者:島上碼農(nóng)  
在原生的?Android?或?iOS?中,都提供了基本的鍵值對(duì)存儲(chǔ)方式,在?Flutter?中,提供了?shared_preferences?這個(gè)插件來(lái)實(shí)現(xiàn)本地鍵值對(duì)數(shù)據(jù)存儲(chǔ),本文就來(lái)和大家簡(jiǎn)單聊聊吧

前言

在原生的 Android 或 iOS 中,都提供了基本的鍵值對(duì)存儲(chǔ)方式,Android 是 SharedPreferences,iOS 是 NSUserDefaults。在 Flutter 中,提供了 shared_preferences 這個(gè)插件來(lái)實(shí)現(xiàn)本地鍵值對(duì)數(shù)據(jù)存儲(chǔ)。實(shí)際上,shared_preferences 在 Android 就是使用 SharedPreferences 實(shí)現(xiàn),在 iOS 上則是使用 NSUserDefaults 實(shí)現(xiàn)。

基本使用

在 pubspec.yaml 文件中添加以下代碼:

dependencies:
    flutter:
        sdk: flutter
    shared_preferences: ^2.0.18

我們將基礎(chǔ)的計(jì)數(shù)應(yīng)用修改為支持從上一次結(jié)果(即存儲(chǔ)在本地的數(shù)值)開(kāi)始增加。代碼如下:

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;
  late SharedPreferences _prefs;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  void _loadCounter() async {
    _prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (_prefs.getInt('counter') ?? 0);
    });
  }

  void _incrementCounter() async {
    setState(() {
      _counter++;
    });
    await _prefs.setInt('counter', _counter);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Shared Preferences 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

上面的代碼是一個(gè)基礎(chǔ)的計(jì)數(shù)器應(yīng)用,我們定義了一個(gè)_counter變量來(lái)保存計(jì)數(shù)器的值,并且使用 SharedPreferences 實(shí)例來(lái)存儲(chǔ)和檢索_counter變量的值。 在initState方法中,我們使用_loadCounter方法來(lái)加載_counter變量的值。在_loadCounter方法中,我們首先使用SharedPreferences.getInstance() 方法來(lái)獲取 SharedPreferences 實(shí)例,然后使用 getInt()方法來(lái)檢索 _counter 變量的值。如果檢索到的值為 null,則將 _counter 變量的值設(shè)置為 0。 在 _incrementCounter 方法中,我們使用了setInt方法將 _counter 變量的值保存到 SharedPreferences 實(shí)例中來(lái)實(shí)現(xiàn)本地存儲(chǔ)。 運(yùn)行效果如下:

存儲(chǔ)其他類型數(shù)據(jù)

shared_preferences支持存儲(chǔ)的數(shù)據(jù)類型有整型、浮點(diǎn)型(double)、字符串、布爾型和字符串?dāng)?shù)組。如果想存儲(chǔ)對(duì)象,也可以通過(guò) json 序列化和反序列化的方式實(shí)現(xiàn)。我們來(lái)看一個(gè)更復(fù)雜點(diǎn)的例子。

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 初始化需要存儲(chǔ)的值
  int _counter = 0;
  String _username = '';
  bool _isDarkModeEnabled = false;
  final _textController = TextEditingController(text: '');

  // SharedPreferences 實(shí)例
  late SharedPreferences _prefs;

  // 加載 SharedPreferences 中存儲(chǔ)的值
  Future<void> _loadData() async {
    _prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = _prefs.getInt('counter') ?? 0;
      _username = _prefs.getString('username') ?? '';
      _textController.text = _username;
      _isDarkModeEnabled = _prefs.getBool('isDarkModeEnabled') ?? false;
    });
  }

  void _incrementCounter() async {
    setState(() {
      _counter++;
    });
    await _prefs.setInt('counter', _counter);
  }

  // 保存用戶名
  void _saveUsername(String username) async {
    setState(() {
      _username = username;
    });
    await _prefs.setString('username', _username);
  }

  // 切換暗黑模式
  void _toggleDarkMode(bool isDarkModeEnabled) async {
    setState(() {
      _isDarkModeEnabled = isDarkModeEnabled;
    });
    await _prefs.setBool('isDarkModeEnabled', _isDarkModeEnabled);
  }

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SharedPreferences 示例',
      theme: _isDarkModeEnabled ? ThemeData.dark() : ThemeData.light(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter SharedPreferences 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '計(jì)數(shù)器的值:$_counter',
              ),
              const SizedBox(height: 20),
              TextFormField(
                decoration: const InputDecoration(
                  labelText: '請(qǐng)輸入您的名字',
                ),
                controller: _textController,
                onChanged: (value) {
                  _saveUsername(value);
                },
              ),
              const SizedBox(height: 20),
              SwitchListTile(
                title: const Text('啟用暗黑模式'),
                value: _isDarkModeEnabled,
                onChanged: (value) {
                  _toggleDarkMode(value);
                },
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          tooltip: '遞增計(jì)數(shù)器的值',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

上述代碼增加了兩個(gè)類型的存儲(chǔ),分別是字符串和布爾型,存儲(chǔ)方式其實(shí)是類似的,布爾型使用 getBool 獲取、setBool 存儲(chǔ);字符串則是使用 getStringsetString。我們通過(guò)布爾型變量控制是否啟用暗黑模式,使用字符串類存儲(chǔ)用戶名。下面是運(yùn)行的結(jié)果。

總結(jié)

可以看到shared_preferences 非常簡(jiǎn)單,因此可以應(yīng)用在簡(jiǎn)單的鍵值對(duì)存儲(chǔ)中,典型的就是我們?cè)诒镜負(fù)Q成后端的SessionId、記住用戶名和密碼、或者默認(rèn)的勾選項(xiàng)等等。然后基于這些存儲(chǔ)的數(shù)據(jù)做默認(rèn)值顯示和業(yè)務(wù)規(guī)則控制、或填充到請(qǐng)求表單里。對(duì)于復(fù)雜的業(yè)務(wù)對(duì)象存儲(chǔ),則需要使用 SQL數(shù)據(jù)庫(kù)或者是 NoSQL 數(shù)據(jù)庫(kù)。

到此這篇關(guān)于Flutter本地存儲(chǔ)之基本的鍵值對(duì)存儲(chǔ)詳解的文章就介紹到這了,更多相關(guān)Flutter鍵值存儲(chǔ)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論