DEV Community

Alexandre Freire
Alexandre Freire

Posted on

Flutter shared_preferences

Envolve NSUserDefaults (no iOS) e SharedPreferences (no Android), fornecendo um armazenamento persistente para dados simples. Os dados são mantidos no disco de forma assíncrona. Nenhuma plataforma pode garantir que as gravações serão mantidas no disco após o retorno e esse plug-in não deve ser usado para armazenar dados críticos

Uso

Para usar esse plug-in, adicione shared_preferencescomo uma dependência no seu arquivo pubspec.yaml .

1. Instalação

Adicione isso ao arquivo pubspec.yaml do seu pacote:

dependencies:
  shared_preferences: ^0.5.3+4
Enter fullscreen mode Exit fullscreen mode

2. Instale.

Você pode instalar pacotes a partir da linha de comando:

$ flutter pub get
Enter fullscreen mode Exit fullscreen mode

Como alternativa, seu editor pode suportar flutter pub get. Verifique os documentos do seu editor para saber mais.

3. Importe

Agora, no seu código Dart, você pode usar:

import 'package:shared_preferences/shared_preferences.dart';
Enter fullscreen mode Exit fullscreen mode

Exemplo

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

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _incrementCounter,
        child: Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}
Enter fullscreen mode Exit fullscreen mode

Teste

Você pode preencher SharedPreferencescom valores iniciais em seus testes executando este código:

const MethodChannel('plugins.flutter.io/shared_preferences')
  .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{}; // set initial values here if desired
    }
    return null;
  });
Enter fullscreen mode Exit fullscreen mode

Fonte: https://pub.dev/packages/shared_preferences

Top comments (0)