[flutter] shared_preferences를 활용하여 로그인 정보를 저장하는 방법은?

First, make sure to add the shared_preferences package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.8

Then, run flutter pub get to install the package.

Next, here’s an example of how to use shared_preferences to store and retrieve login information:

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

class LoginScreen extends StatelessWidget {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  Future<void> _saveLoginInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('username', _usernameController.text);
    await prefs.setString('password', _passwordController.text);
  }

  Future<void> _retrieveLoginInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String username = prefs.getString('username');
    String password = prefs.getString('password');
    // Use the retrieved login information for auto-login or other purposes
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login Screen'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextField(
            controller: _usernameController,
            decoration: InputDecoration(labelText: 'Username'),
          ),
          TextField(
            controller: _passwordController,
            decoration: InputDecoration(labelText: 'Password'),
            obscureText: true,
          ),
          ElevatedButton(
            onPressed: _saveLoginInfo,
            child: Text('Save Login Info'),
          ),
          ElevatedButton(
            onPressed: _retrieveLoginInfo,
            child: Text('Retrieve Login Info'),
          ),
        ],
      ),
    );
  }
}

In this example, we use the SharedPreferences.getInstance() method to get an instance of SharedPreferences and then use setString() to save login information and getString() to retrieve it.

Remember, it’s important to handle sensitive information like passwords securely. Always consider encryption or other security measures based on your specific app requirements.

For more information about the shared_preferences package, you can refer to the official documentation: shared_preferences package.

이렇게 하면 shared_preferences 패키지를 사용하여 로그인 정보를 저장하고 검색할 수 있습니다.