Introduzione a flutter_secure_storage

Mattepuffo's logo
Introduzione a flutter_secure_storage

Introduzione a flutter_secure_storage

flutter_secure_storage è un package per Flutter che ci consente di salvare dei dati in maniera sicura.

E' compatibile con tutte le piattaforme:

  • su Android viene usata la AES encryption
  • su iOS viene usato direttamente KeyChain
  • su Linux avete bisogno di libsecret
  • ecc

Purtroppo ho avuto modo di fare solo un test veloce su Android; per l'installazione:

flutter pub add flutter_secure_storage

Qui un codice di esempio:

import 'dart:math';

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Test',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _storage = const FlutterSecureStorage();
  List<Items> _items = [];

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

  IOSOptions _iosOptions() => const IOSOptions(
        accountName: 'ACCOUNT_NAME',
      );

  AndroidOptions _androidOptions() => const AndroidOptions(
        encryptedSharedPreferences: true,
      );

  Future<void> _readAll() async {
    final all = await _storage.readAll(
      iOptions: _iosOptions(),
      aOptions: _androidOptions(),
    );
    setState(() {
      _items = all.entries
          .map((entry) => Items(entry.key, entry.value))
          .toList(growable: false);
    });
  }

  Future<void> _deleteAll() async {
    await _storage.deleteAll(
      iOptions: _iosOptions(),
      aOptions: _androidOptions(),
    );
    _readAll();
  }

  Future<void> _add() async {
    final String key = _randomValue();
    final String value = _randomValue();

    await _storage.write(
      key: key,
      value: value,
      iOptions: _iosOptions(),
      aOptions: _androidOptions(),
    );
    _readAll();
  }

  String _randomValue() {
    final rand = Random();
    final codeUnits = List.generate(20, (index) {
      return rand.nextInt(26) + 65;
    });

    return String.fromCharCodes(codeUnits);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('Flutter Test'),
      ),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              _add();
              _items.forEach((el) {
                print("${el.key}: ${el.value}");
              });
            },
            child: const Text('AGGIUNGI!'),
          ),
          ElevatedButton(
            onPressed: () {
              _deleteAll();
              _items.forEach((el) {
                print("${el.key}: ${el.value}");
              });
            },
            child: const Text('CANCELLA TUTTO!'),
          ),
        ],
      ),
    );
  }
}

class Items {
  Items(this.key, this.value);

  final String key;
  final String value;
}

Enjoy!


Condividi

Commentami!