美文网首页
Flutter 缓存数据组件

Flutter 缓存数据组件

作者: Albert新荣 | 来源:发表于2020-12-23 14:24 被阅读0次

    shared_preferences

    shared_preferences: ^0.5.12+4
    

    使用实例

    import 'dart:async';
    
    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'SharedPreferences Demo',
          home: SharedPreferencesDemo(),
        );
      }
    }
    
    class SharedPreferencesDemo extends StatefulWidget {
      SharedPreferencesDemo({Key key}) : super(key: key);
    
      @override
      SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
    }
    
    class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
      Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
      Future<int> _counter;
    
      Future<void> _incrementCounter() async {
        final SharedPreferences prefs = await _prefs;
        final int counter = (prefs.getInt('counter') ?? 0) + 1;
    
        setState(() {
          _counter = prefs.setInt("counter", counter).then((bool success) {
            return counter;
          });
        });
      }
    
      @override
      void initState() {
        super.initState();
        _counter = _prefs.then((SharedPreferences prefs) {
          return (prefs.getInt('counter') ?? 0);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("SharedPreferences Demo"),
          ),
          body: Center(
              child: FutureBuilder<int>(
                  future: _counter,
                  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.waiting:
                        return const CircularProgressIndicator();
                      default:
                        if (snapshot.hasError) {
                          return Text('Error: ${snapshot.error}');
                        } else {
                          return Text(
                            'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
                            'This should persist across restarts.',
                          );
                        }
                    }
                  })),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    

    相关文章

      网友评论

          本文标题:Flutter 缓存数据组件

          本文链接:https://www.haomeiwen.com/subject/hlnynktx.html