{"id":362,"date":"2025-07-06T22:30:29","date_gmt":"2025-07-06T14:30:29","guid":{"rendered":"https:\/\/www.bqmz001.top\/?p=362"},"modified":"2025-07-06T22:30:29","modified_gmt":"2025-07-06T14:30:29","slug":"flutter-%e9%a6%96%e9%a1%b5%e5%88%b6%e4%bd%9c%e5%92%8csharedpreference","status":"publish","type":"post","link":"https:\/\/www.bqmz001.top\/index.php\/2025\/07\/06\/flutter-%e9%a6%96%e9%a1%b5%e5%88%b6%e4%bd%9c%e5%92%8csharedpreference\/","title":{"rendered":"flutter \u9996\u9875\u5236\u4f5c\u548cSharedPreference"},"content":{"rendered":"<h2>1\u3001\u9996\u9875\u600e\u4e48\u505a\uff1f<\/h2>\n<p>\u8fd9\u56de\u65b0\u5efa\u4e86\u4e00\u4e2a\u9879\u76ee\uff0c\u5b8c\u5168\u7684\u4ece\u5934\u5f00\u59cb\u3002<\/p>\n<pre><code>import &#039;package:day08\/sp_demo.dart&#039;;\nimport &#039;package:flutter\/material.dart&#039;;\nimport &#039;package:flutter\/services.dart&#039;;\nimport &#039;package:flutter\/widgets.dart&#039;;\nimport &#039;package:flutter_styled_toast\/flutter_styled_toast.dart&#039;;\n\n\nvoid main() {\n  runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  const MyApp({super.key});\n\n  \/\/ This widget is the root of your application.\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: &#039;Flutter Demo&#039;,\n      theme: ThemeData(\n        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),\n      ),\n      home: const MyHomePage(title: &#039;Flutter Demo Home Page&#039;),\n    );\n  }\n}\n\nclass MyHomePage extends StatefulWidget {\n  const MyHomePage({super.key, required this.title});\n  final String title;\n\n  @override\n  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();\n}\n\nclass _MyHomePageState extends State&lt;MyHomePage&gt; {\n\n  int _currentIndex = 0;\n\n  final List&lt;Widget&gt; _pages = [\n    const Center(child: Text(&#039;\u9996\u9875&#039;)),\n    const Center(child: Text(&#039;\u53d1\u73b0&#039;)),\n    const Center(child: Text(&#039;\u6211\u7684&#039;)),\n  ];\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n        appBar: AppBar(\n          backgroundColor: Theme.of(context).colorScheme.inversePrimary,\n          title: Text(widget.title),\n        ),\n        body: _pages[_currentIndex],\n        floatingActionButton: FloatingActionButton(\n          onPressed: _incrementCounter,\n          tooltip: &#039;Increment&#039;,\n          child: const Icon(Icons.add),\n        ),\n        bottomNavigationBar: BottomNavigationBar(\n          currentIndex: _currentIndex,\n          onTap: (index) {\n            setState(() {\n              _currentIndex = index;\n            });\n          },\n          items: const [\n            BottomNavigationBarItem(\n              icon: Icon(Icons.home),\n              label: &#039;\u9996\u9875&#039;,\n            ),\n            BottomNavigationBarItem(\n              icon: Icon(Icons.search),\n              label: &#039;\u53d1\u73b0&#039;,\n            ),\n            BottomNavigationBarItem(\n              icon: Icon(Icons.person),\n              label: &#039;\u6211\u7684&#039;,\n            ),\n          ],\n        ),\n      );\n  }\n}\n<\/code><\/pre>\n<p>\u4e00\u822c\u9875\u9762\u7ed3\u6784\u5c31\u662fAppBar-Body-BottomNavigationBar\u3002\u672c\u6765\u8fd8\u60f3\u7740\u5728body\u4e0b\u65b9\u5199\u4e00\u4e2a\u5c0f\u5730\u65b9\u653eBottomNavigationBar\u6765\u7740\uff0c\u6ca1\u60f3\u5230\u6709\u69fd\u4f4d\uff0c\u90a3\u5c31\u8001\u5b9e\u70b9\u653e\u69fd\u4f4d\u5427\u3002<\/p>\n<p>BottomNavigationBar\u4e5f\u5c31\u662f\u8089\u773c\u53ef\u89c1\u7684\u4ee8\u5730\u65b9\uff1a<br \/><code>currentIndex<\/code>:\u4f4d\u7f6e\u4e0b\u6807\uff1b<br \/><code>onTap:(index){}<\/code>:\u70b9\u51fb\u4e8b\u4ef6\uff0csetState\u5237\u65b0\u9875\u9762\u5e72\u5457\uff1b<br \/><code>items<\/code>:\u6570\u7ec4\u653e\u5e95\u90e8\u5bfc\u822a\u680f\u6309\u94ae\uff0c\u5c31\u76f4\u63a5\u5199BottomNavigationBarItem\u5c31\u884c\uff0c\u6284\uff01<br \/><em>\u4e0d\u8fc7Material3\u4e3b\u9898\u653eMaterial2\u6837\u5f0f\u7684BottomNavigationBar\u2014\u2014\u867d\u7136\u786e\u5b9e\u4e0d\u5408\u9002\uff0c\u4f46\u7b26\u5408\u6211\u56fd\u4e1a\u52a1\u5f00\u53d1\u7684\u56fd\u60c5\u3002\u8d77\u7801\u4e2d\u5eb8\u662f\u6b63\u786e\u7684\u2014\u2014\u6bd5\u7adf\u73b0\u5728\u82f9\u679c\u7684\u201c\u8d85\u7ea7\u6bdb\u73bb\u7483\u201d\u5c31\u6682\u65f6\u6765\u8bb2\u56fd\u5185\u5927\u90e8\u5206\u60c5\u51b5\u662f\u4e0d\u4f1a\u8ddf\u3002<\/em><\/p>\n<p>body\u91cc\u9762\u76f4\u63a5\u5c31\u662f\u9875\u9762\u7684\u5217\u8868\u6570\u7ec4\uff0c\u6839\u636e\u4e0b\u6807\u663e\u793a\u3002<\/p>\n<h2>2\u3001\u9996\u9875\u7684\u201c\u518d\u6309\u4e00\u6b21\u9000\u51fa\u201d\u95ee\u9898<\/h2>\n<p>ios\u4e0a\u53ef\u80fd\u4e0d\u4f1a\u5b58\u5728\uff0c\u56e0\u4e3aios\u538b\u6839\u4e0d\u5b58\u5728\u5168\u5c40\u8fd4\u56de\u6309\u94ae\uff0c\u81ea\u7136\u4e5f\u5c31\u6ca1\u8fd9\u4e00\u8bf4\u2014\u2014\u53ef\u6211\u662f\u4e2aAndroid\u4f6c\u6b38\uff01<br \/>\u641e\u4e00\u4e0b\u5427\uff01<\/p>\n<pre><code>DateTime? _lastPressedAt; \/\/ \u8bb0\u5f55\u4e0a\u6b21\u70b9\u51fb\u65f6\u95f4\n\nWidget build(BuildContext context) {\n    return WillPopScope(\n      onWillPop: () async {\n        if (_lastPressedAt == null ||\n            DateTime.now().difference(_lastPressedAt!) &gt; const Duration(seconds: 2)) {\n          \/\/ \u4e24\u6b21\u70b9\u51fb\u95f4\u9694\u8d85\u8fc72\u79d2\uff0c\u663e\u793a\u63d0\u793a\n          _lastPressedAt = DateTime.now();\n          showToast(\n             context: context,\n             &#039;\u518d\u6309\u4e00\u6b21\u9000\u51fa\u5e94\u7528&#039;,\n             duration: const Duration(seconds: 2),\n           );\n          return false;\n        }\n        \/\/ \u4e24\u6b21\u70b9\u51fb\u95f4\u9694\u5c0f\u4e8e2\u79d2\uff0c\u9000\u51fa\u5e94\u7528\n        return true;\n      },\n      child: Scaffold(\n        \/\/Scaffold\u5185\u5bb9\u7701\u7565\n      ),\n    );\n  }\n<\/code><\/pre>\n<p>\u5927\u81f4\u9053\u7406\u6211\u61c2\uff01\u4e5f\u8fd8\u662fAndroid\u8001\u5957\u8def\uff1a<br \/><strong>\u7b2c\u4e00\u6b21 \u6216 \u95f4\u9694\u8d85\u8fc7\u8bbe\u5b9a\u65f6\u95f4\u540e\uff08\u8fd9\u91cc\u662f2\u79d2\uff09<\/strong>\uff1a\u8bb0\u4e0b\u5f53\u524d\u65f6\u95f4\uff0c\u7136\u540e\u7ed9\u4e00\u4e2a\u63d0\u793a<br \/><strong>\u5728\u7b2c\u4e00\u6b21\u64cd\u4f5c\u95f4\u9694\u65f6\u95f4\u5185\u7b2c\u4e8c\u6b21\u64cd\u4f5c<\/strong>\uff1a\u6267\u884c\u9000\u51fa\u64cd\u4f5c\u3002<\/p>\n<p><strong>\u4f46\u662f\uff01<\/strong> WillPopScope\u5728flutter 3.12+\u88ab\u5f03\u7528&#8230;&#8230;\u6539\u7528PopScope\u5566\uff01<\/p>\n<pre><code>  DateTime? _lastPressedAt; \/\/ \u8bb0\u5f55\u4e0a\u6b21\u70b9\u51fb\u65f6\u95f4\n\n  bool _canPop = false; \/\/ \u63a7\u5236\u662f\u5426\u5141\u8bb8\u8fd4\u56de\n  \n  @override\n  Widget build(BuildContext context) {\n    return PopScope(\n      canPop: _canPop,\n      onPopInvokedWithResult: (didPop, result) async { \n        if (didPop) return; \/\/ \u5df2\u5904\u7406\u5f39\u51fa\u5219\u76f4\u63a5\u8fd4\u56de\n        if(_currentIndex != 0){\n          setState(() {\n            _currentIndex = 0;\n          });\n          return;\n        }else{\n          final now = DateTime.now();\n          if (_lastPressedAt == null || now.difference(_lastPressedAt!) &gt; const Duration(seconds: 2)) {\n            _lastPressedAt = now;\n            showToast(\n              context: context,\n              &#039;\u518d\u6309\u4e00\u6b21\u9000\u51fa\u5e94\u7528&#039;,\n              duration: const Duration(seconds: 2),\n            );\n            return;\n          }\n          _canPop=true;\n          if (mounted) {\n            SystemNavigator.pop();\n          }\n        }\n\n      },\n      child: Scaffold(\n        \/\/Scaffold\u5185\u5bb9\u7701\u7565\n      ),\n    );\n  }\n<\/code><\/pre>\n<p>\u81f3\u5c11\u8fd9\u4e2a\u5199\u6cd5IDE\u4e0d\u4f1a\u62a5\u9519\uff0c\u4e5f\u4e0d\u4f1a\u6267\u884c\u5931\u7075\u3002<br \/>\u65b0\u589e\u7684canPop\u53c2\u6570\u5c31\u662f\u63a7\u5236\u8ba9\u4e0d\u8ba9\u5f39\u51fa\u7684\uff0c\u4f46\u4e0d\u8fc7true\u8fd8\u662ffalse\u90fd\u662f\u8981\u7ecf\u8fc7onPopInvokedWithResult\u56de\u8c03\uff08\u524d\u7aef\u79f0\u4e4b\u4e3a\u94a9\u5b50\uff09\u3002<br \/><code>if (didPop) return;<\/code>\u5904\u7406\u8fc7\u5c31\u76f4\u63a5\u4e0d\u5904\u7406\u4e86\u3002\u6ca1\u5904\u7406\u624d\u6709\u63a5\u4e0b\u6765\u7684\u4e8b\u60c5\uff1a\u9996\u5148\u5982\u679c\u4e0d\u662f\u9996\u9875\u7684\u8bdd\u5148\u8fd4\u56de\u9996\u9875\uff0c\u7136\u540e\u5c31\u662f\u8001\u5957\u8def\u8bb0\u4e0b\u5f53\u524d\u65f6\u95f4\uff0c\u7b2c\u4e8c\u6b21\u6309\u4e0b\u8fd4\u56de\u952e\u65f6\u6267\u884c\u9000\u51fa\u64cd\u4f5c\u3002<br \/>\u5148\u628acanPop\u6539\u4e3atrue\u8ba9\u9875\u9762\u5141\u8bb8\u9000\u51fa\uff0c\u7136\u540e<code>SystemNavigator.pop()<\/code>\u9000\u51fa\u3002\u7f51\u4e0a\u8bf4\u7684\u662fAndroid\u539f\u751f\u90e8\u5206\u8fd8\u8981\u5904\u7406\u4e1c\u897f\u4e86\u5c31\u62ff\u8fd9\u4e2a\u9000\u51fa\u5c31\u884c\u3002\u5982\u679c\u6ca1\u6709\u5c31\u76f4\u63a5<code>exit(0)<\/code>\u4e5f\u5e76\u975e\u4e0d\u53ef\u3002\u4e2a\u4eba\u8ba4\u4e3a\u5728\u5b89\u5353\u4e0a\u4fe9\u90fd\u80fd\u968f\u4fbf\u7528\uff0c\u53cd\u6b63\u7eafflutter\u9879\u76ee\u6548\u679c\u4e00\u6837\u3002<\/p>\n<p>ios\uff1f\u4e0d\u7ba1\uff01\u53cd\u6b63\u4ed6\u4eec\u6ca1\u6709\u5168\u5c40\u8fd4\u56de\u952e\uff0c\u7ba1\u597d\u81ea\u5df1\u8fd4\u56de\u6808\u4e0d\u7528\u4e86\u76f4\u63a5\u4e0a\u5212\u5c0f\u6a2a\u6761\u5212\u56de\u684c\u9762\u6216\u8005\u540e\u53f0\u5212\u6389\u5c31\u6ca1\u5565\u4e8b\u4e86\uff0c\u64cd\u90a3\u4e48\u591a\u5fc3\u5e72\u561b\u3002<\/p>\n<h2>3\u3001\u8bd5\u4e00\u4e0bSharedPreference<\/h2>\n<p>\u9996\u5148\u7ed9\u4e2a\u5730\u65b9\u8fdb\u5165\u65b0\u7684SharedPreference\u6d4b\u8bd5\u9875\u9762<\/p>\n<pre><code>import &#039;package:day08\/sp_demo.dart&#039;;\nimport &#039;package:flutter\/material.dart&#039;;\nimport &#039;package:flutter\/services.dart&#039;;\nimport &#039;package:flutter\/widgets.dart&#039;;\nimport &#039;package:flutter_styled_toast\/flutter_styled_toast.dart&#039;;\n\n\nvoid main() {\n  runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n  const MyApp({super.key});\n\n  \/\/ This widget is the root of your application.\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: &#039;Flutter Demo&#039;,\n      theme: ThemeData(\n        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),\n      ),\n      home: const MyHomePage(title: &#039;Flutter Demo Home Page&#039;),\n    );\n  }\n}\n\nclass MyHomePage extends StatefulWidget {\n  const MyHomePage({super.key, required this.title});\n  final String title;\n\n  @override\n  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();\n}\n\nclass _MyHomePageState extends State&lt;MyHomePage&gt; {\n  int _currentIndex = 0;\n  DateTime? _lastPressedAt; \/\/ \u8bb0\u5f55\u4e0a\u6b21\u70b9\u51fb\u65f6\u95f4\n\n  bool _canPop = false; \/\/ \u63a7\u5236\u662f\u5426\u5141\u8bb8\u8fd4\u56de\n\n  final List&lt;Widget&gt; _pages = [\n    const _HomePage(),\n    const Center(child: Text(&#039;\u53d1\u73b0&#039;)),\n    const Center(child: Text(&#039;\u6211\u7684&#039;)),\n  ];\n\n  void _incrementCounter() {\n    setState(() {\n      \/\/ \u539f\u6709\u903b\u8f91\n    });\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return PopScope(\n      canPop: _canPop,\n      onPopInvokedWithResult: (didPop, result) async { \/\/ \u4fee\u6539\u4e3a onPopInvokedWithResult [[1]][[2]]\n        if (didPop) return; \/\/ \u5df2\u5904\u7406\u5f39\u51fa\u5219\u76f4\u63a5\u8fd4\u56de\n        if(_currentIndex != 0){\n          setState(() {\n            _currentIndex = 0;\n          });\n          return;\n        }else{\n          final now = DateTime.now();\n          if (_lastPressedAt == null || now.difference(_lastPressedAt!) &gt; const Duration(seconds: 2)) {\n            _lastPressedAt = now;\n            showToast(\n              context: context,\n              &#039;\u518d\u6309\u4e00\u6b21\u9000\u51fa\u5e94\u7528&#039;,\n              duration: const Duration(seconds: 2),\n            );\n            return;\n          }\n          _canPop=true;\n          if (mounted) {\n            SystemNavigator.pop();\n          }\n        }\n\n      },\n      child: Scaffold(\n        appBar: AppBar(\n          backgroundColor: Theme.of(context).colorScheme.inversePrimary,\n          title: Text(widget.title),\n        ),\n        body: _pages[_currentIndex],\n        floatingActionButton: FloatingActionButton(\n          onPressed: _incrementCounter,\n          tooltip: &#039;Increment&#039;,\n          child: const Icon(Icons.add),\n        ),\n        bottomNavigationBar: BottomNavigationBar(\n          currentIndex: _currentIndex,\n          onTap: (index) {\n            setState(() {\n              _currentIndex = index;\n            });\n          },\n          items: const [\n            BottomNavigationBarItem(\n              icon: Icon(Icons.home),\n              label: &#039;\u9996\u9875&#039;,\n            ),\n            BottomNavigationBarItem(\n              icon: Icon(Icons.search),\n              label: &#039;\u53d1\u73b0&#039;,\n            ),\n            BottomNavigationBarItem(\n              icon: Icon(Icons.person),\n              label: &#039;\u6211\u7684&#039;,\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n}\n\nclass _HomePage extends StatelessWidget {\n  const _HomePage({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return Center(\n      child: Column(\n        mainAxisAlignment: MainAxisAlignment.center,\n        children: [\n          const Text(&#039;\u9996\u9875&#039;),\n          ElevatedButton(\n            onPressed: () {\n              Navigator.push(\n                context,\n                MaterialPageRoute(builder: (context) =&gt; const SharedPreferencesDemoPage()),\n              );\n            },\n            child: const Text(&#039;\u8df3\u8f6c\u5230 SharedPreferences \u793a\u4f8b\u9875\u9762&#039;),\n          ),\n        ],\n      ),\n    );\n  }\n}\n<\/code><\/pre>\n<p>\u7136\u540e\u8fdb\u5165\u65b0\u7684SharedPreferencesDemoPage\uff1a<\/p>\n<pre><code>import &#039;package:flutter\/material.dart&#039;;\nimport &#039;package:shared_preferences\/shared_preferences.dart&#039;;\n\nclass SharedPreferencesDemoPage extends StatefulWidget {\n  const SharedPreferencesDemoPage({super.key});\n\n  @override\n  State&lt;SharedPreferencesDemoPage&gt; createState() =&gt; _SharedPreferencesDemoPageState();\n}\n\nclass _SharedPreferencesDemoPageState extends State&lt;SharedPreferencesDemoPage&gt; {\n  String _storedValue = &#039;&#039;;\n  final TextEditingController _textController = TextEditingController();\n\n  @override\n  void initState() {\n    super.initState();\n    _loadValue();\n  }\n\n  Future&lt;void&gt; _saveValue() async {\n    final prefs = await SharedPreferences.getInstance();\n    await prefs.setString(&#039;demo_key&#039;, _textController.text);\n    _loadValue();\n  }\n\n  Future&lt;void&gt; _loadValue() async {\n    final prefs = await SharedPreferences.getInstance();\n    setState(() {\n      _storedValue = prefs.getString(&#039;demo_key&#039;) ?? &#039;&#039;;\n    });\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: const Text(&#039;SharedPreferences \u793a\u4f8b&#039;),\n      ),\n      body: Center(\n        child: Column(\n          mainAxisAlignment: MainAxisAlignment.center,\n          children: [\n            TextField(\n              controller: _textController,\n              decoration: const InputDecoration(\n                labelText: &#039;\u8f93\u5165\u8981\u4fdd\u5b58\u7684\u503c&#039;,\n              ),\n            ),\n            ElevatedButton(\n              onPressed: _saveValue,\n              child: const Text(&#039;\u4fdd\u5b58&#039;),\n            ),\n            Text(&#039;\u5b58\u50a8\u7684\u503c: $_storedValue&#039;),\n          ],\n        ),\n      ),\n    );\n  }\n}\n<\/code><\/pre>\n<p>\u5927\u6982\u5c31\u8fd9\u4e2a\u6837\u5b50\u3002\u4e5f\u5c31\u662f<code>final prefs = await SharedPreferences.getInstance()<\/code>\u3001<code>prefs.getString(&#039;demo_key&#039;) ?? &#039;&#039;<\/code>\u548c<code>await prefs.setString(&#039;demo_key&#039;, _textController.text)<\/code><br \/>\u548cAndroid\u91cc\u7684\u601d\u8def\u662f\u5dee\u4e0d\u591a\u7684\uff0c\u8fd9\u4e2a\u57fa\u672c\u6ca1\u5565\u5927\u7684\u53d8\u52a8\uff0c\u62ff\u5b9e\u4f8b-\u5199-\u8bfb\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1\u3001\u9996\u9875\u600e\u4e48\u505a\uff1f \u8fd9\u56de\u65b0\u5efa\u4e86\u4e00\u4e2a\u9879\u76ee\uff0c\u5b8c\u5168\u7684\u4ece\u5934\u5f00\u59cb\u3002 import &#039;package:day08\/ [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[],"class_list":["post-362","post","type-post","status-publish","format-standard","hentry","category-androidflutter"],"_links":{"self":[{"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/posts\/362","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/comments?post=362"}],"version-history":[{"count":47,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/posts\/362\/revisions"}],"predecessor-version":[{"id":409,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/posts\/362\/revisions\/409"}],"wp:attachment":[{"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/media?parent=362"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/categories?post=362"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bqmz001.top\/index.php\/wp-json\/wp\/v2\/tags?post=362"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}