꿈꾸는 시스템 디자이너

Flutter Example - Shared Preferences 본문

Tutorial/Flutter with App

Flutter Example - Shared Preferences

독행소년 2019. 9. 26. 22:11

Add this to pubspec.yaml file

dependencies:
  shared_preferences: ^0.5.3+4

 

Source Code

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

SharedPreferencesDemoState pageState;

class SharedPreferencesDemo extends StatefulWidget {
  @override
  SharedPreferencesDemoState createState() {
    pageState = SharedPreferencesDemoState();
    return pageState;
  }
}

class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
  int counter;

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

  getCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      counter = (prefs.getInt("counter") ?? 0);
    });
  }

  setCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("counter", counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Shared Preferences Demo")),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            SizedBox(
              height: 40,
              child: FloatingActionButton(
                heroTag: "add",
                child: Icon(Icons.remove),
                onPressed: () {
                  setState(() {
                    counter--;
                  });
                  setCounter();
                },
              ),
            ),
            Text("Shared preferences value: "),
            Text(
              "${counter.toString()}",
              style: TextStyle(fontSize: 30),
            ),
            SizedBox(
              height: 40,
              child: FloatingActionButton(
                heroTag: "remove",
                child: Icon(Icons.add),
                onPressed: () {
                  setState(() {
                    counter++;
                  });
                  setCounter();
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

 

 

▶ Go to Table of Contents | 강의 목차로 이동


※ This example is also available in the Flutter Code Examples app. | 본 예제는 Flutter Code Examples 앱에서도 제공됩니다.

 

Flutter Code Examples - Google Play 앱

Are you a beginner at Flutter? Check out the various features of Flutter through the demo. Source code for all demos is also provided.

play.google.com

Comments