Flutter Package : Shared Preferences

Flutter Package : Shared Preferences

pubspec.yaml

shared_preferences: ^0.5.3+4

main.dart

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

void main() {
  runApp(Home());
}

class Home extends StatefulWidget {
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String title = "Shared Preferences";
  Color bgColor = Colors.redAccent;
  Color fgColor = Colors.white;
  IconData icLogo = Icons.star_border;
  final _title = TextEditingController();

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

  void _SaveData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setString('title', _title.text);
      prefs.setString('bgColor', _title.text);
      title = prefs.getString("title");
      bgColor = prefs.getString("bgColor");
    });
  }

  void _GetData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _title.text = prefs.getString("title");
      title = prefs.getString("title");
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: title,
      home: Scaffold(
        backgroundColor: fgColor,
        appBar: new AppBar(
          backgroundColor: bgColor,
          leading: Icon(icLogo),
          title: Text(title),
        ),
        body: Column(
          children: <Widget>[
            TextField(
              controller: _title,
              decoration: InputDecoration(filled: true, labelText: 'Title'),
            ),
            // spasi
            SizedBox(height: 5.0),

            Row(
              children: <Widget>[
                RaisedButton(
                  child: Text("Save"),
                  onPressed: () {
                    _SaveData();
                  },
                ),
                RaisedButton(
                  child: Text("Get"),
                  onPressed: () {
                    _GetData();
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

Flutter Developer