Home » Blog » Flutter : How to use UserProvider after login and consume it in other widgets

Flutter : How to use UserProvider after login and consume it in other widgets

To save the login state of a user in Flutter using the Provider package, you can follow these steps:

  1. First, install the Provider package by adding it to your pubspec.yaml file and running flutter pub get.
  2. Next, create a User model class to store the relevant information about the logged-in user. This might include the user’s name, email, and any other details you want to store.
  3. Create a UserProvider class that extends ChangeNotifier and contains an instance of your User model class. This provider class will be responsible for storing and updating the login state of the user.
  4. In your main.dart file, wrap your app with a ChangeNotifierProvider widget, passing in an instance of your UserProvider class as the value.
  5. In any widget where you want to access the login state of the user, you can use a Consumer widget to access the UserProvider and the User model it contains.

To save API data in a UserProvider after logging in with Flutter, you can follow these steps:

  1. Create a UserProvider class that will hold the data you want to save. This class should extend ChangeNotifier and implement the dispose method:
Copy codeimport 'package:flutter/widgets.dart';

class UserProvider extends ChangeNotifier {
  // Data that you want to save goes here
  String _username;
  String _token;

  String get username => _username;
  String get token => _token;

  void setUser(String username, String token) {
    _username = username;
    _token = token;
    notifyListeners();
  }

  @override
  void dispose() {
    super.dispose();
  }
}
  1. In your login screen, make an HTTP request to the API to log the user in. If the login is successful, save the data that you want to persist (e.g. username, token) in the UserProvider:
Copy codeimport 'package:your_app/user_provider.dart';

// ...

final userProvider = Provider.of<UserProvider>(context, listen: false);

// ...

void _login() async {
  // Make HTTP request to log in
  final response = await http.post(loginUrl, body: {
    'username': _usernameController.text,
    'password': _passwordController.text,
  });

  if (response.statusCode == 200) {
    // Save data in user provider
    final data = json.decode(response.body);
    userProvider.setUser(data['username'], data['token']);
  } else {
    // Handle error
  }
}
  1. To consume the data saved in the UserProvider, wrap the widget that needs access to the data with a Provider widget. Then, use the Provider.of method to access the data in the UserProvider:
Copy codeimport 'package:flutter/widgets.dart';
import 'package:your_app/user_provider.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);

    return Scaffold(
      // Use data from user provider
      body: Text('Welcome, ${userProvider.username}'),
    );
  }
}
  1. In your main file, wrap your entire app with a MultiProvider widget and provide an instance of the UserProvider:
Copy codeimport 'package:flutter/material.dart';
import 'package:your_app/user_provider.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => UserProvider()),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  // ...
}

This will allow you to access the data saved in the UserProvider from any widget in your app.