> ## Documentation Index
> Fetch the complete documentation index at: https://docs.getpara.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter Session Management

> Guide to managing authentication sessions in Para for Flutter applications

export const Card = ({imgUrl, title, description, href, horizontal = false, newTab = false}) => {
  const [isHovered, setIsHovered] = useState(false);
  const handleClick = e => {
    e.preventDefault();
    if (newTab) {
      window.open(href, '_blank', 'noopener,noreferrer');
    } else {
      window.location.href = href;
    }
  };
  return <div className={`not-prose relative my-2 p-[1px] rounded-xl transition-all duration-300 ${isHovered ? 'bg-gradient-to-r from-[#FF4E00] to-[#874AE3]' : 'bg-gray-200'}`} onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)}>
      <a href={href} onClick={handleClick} className={`not-prose flex ${horizontal ? 'flex-row' : 'flex-col'} font-normal h-full bg-white overflow-hidden w-full cursor-pointer rounded-[11px] no-underline`}>
        {imgUrl && <div className={`relative overflow-hidden flex-shrink-0 ${horizontal ? 'w-[30%] rounded-l-[11px]' : 'w-full'}`} onClick={e => e.stopPropagation()}>
            <img src={imgUrl} alt={title} className="w-full h-full object-cover pointer-events-none select-none" draggable="false" />
            <div className="absolute inset-0 pointer-events-none" />
          </div>}
        <div className={`flex-grow px-6 py-5 ${horizontal ? 'w-[70%]' : 'w-full'} flex flex-col ${horizontal && imgUrl ? 'justify-center' : 'justify-start'}`}>
          {title && <h2 className="font-semibold text-base text-gray-800 m-0">{title}</h2>}
          {description && <div className={`font-normal text-gray-500 re leading-6 ${horizontal || !imgUrl ? 'mt-0' : 'mt-1'}`}>
              <p className="m-0 text-xs">{description}</p>
            </div>}
        </div>
      </a>
    </div>;
};

export const Link = ({href, label, newTab = false}) => {
  const [isHovered, setIsHovered] = useState(false);
  return <a href={href} target={newTab ? '_blank' : '_self'} rel={newTab ? 'noopener noreferrer' : undefined} className="not-prose inline-block relative text-black font-semibold cursor-pointer border-b-0 no-underline" onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)}>
      {label}
      <span className={`absolute left-0 bottom-0 w-full rounded-sm bg-gradient-to-r from-orange-600 to-purple-600 transition-all duration-300 ${isHovered ? 'h-0.5' : 'h-px'}`} />
    </a>;
};

Para provides a comprehensive set of methods for managing authentication sessions in Flutter applications. These sessions are crucial for secure transaction signing and other authenticated operations.

## Session Duration

Para session length is configured per API key and can be set up to 30 days through the Configuration section of the <Link label="Developer Portal" href="https://developer.getpara.com" /> or CLI. The Para API enforces the configured duration. Signing a message or transaction, or calling the session keep-alive method, can extend an active session according to that configuration.

## Managing Sessions

### Checking Session Status

Use `isSessionActive()` to verify whether a user's session is currently valid before performing authenticated operations.

```dart theme={null}
Future<bool> isSessionActive()
```

<Note>
  In Flutter applications, it's especially important to check the session status before allowing users to access authenticated areas of your app due to the persistence of local storage between app launches.
</Note>

Example usage:

```dart theme={null}
import 'package:para/para.dart';

Future<void> checkSession() async {
  try {
    final isActive = await para.isSessionActive().future;
    if (!isActive) {
      // First clear any existing data
      await para.logout().future;

      // Navigate to login screen
      // Handle navigation according to your app's navigation strategy
    } else {
      // Session is valid, proceed with app flow
      // Navigate to authenticated part of your app
    }
  } catch (e) {
    // Handle error
  }
}
```

### Refreshing Expired Sessions

When a session has expired, Para recommends initiating a full authentication flow rather than trying to refresh the session.

<Warning>
  For Flutter applications, always call `logout()` before reinitiating authentication when a session has expired to ensure all stored data is properly cleared.
</Warning>

```dart theme={null}
import 'package:para/para.dart';

Future<void> handleSessionExpiration() async {
  // When session expires, first clear storage
  await para.logout().future;

  // Then redirect to authentication screen
  // Handle navigation according to your app's navigation strategy
}
```

## Exporting Sessions to Your Server

Use `exportSession()` when you need to transfer session state to your server for performing operations on behalf of the user.

```dart theme={null}
String exportSession()
```

Example implementation:

```dart theme={null}
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:para/para.dart';

Future<Map<String, dynamic>> sendSessionToServer() async {
  // Export session without signing capabilities
  final sessionData = para.exportSession();

  // Send to your server
  try {
    final response = await http.post(
      Uri.parse('https://your-api.com/sessions'),
      headers: {
        'Content-Type': 'application/json',
      },
      body: jsonEncode({'session': sessionData}),
    );

    if (response.statusCode != 200) {
      throw Exception('Failed to send session to server');
    }

    return jsonDecode(response.body);
  } catch (e) {
    // Handle error
    throw e;
  }
}
```

## Best Practices for Flutter

1. **Check Sessions on App Launch**: Verify session status when your app starts to determine if users need to reauthenticate.

```dart theme={null}
import 'package:flutter/material.dart';
import 'package:para/para.dart';

// In your app's entry point or state initialization
@override
void initState() {
  super.initState();
  checkSessionOnLaunch();
}

Future<void> checkSessionOnLaunch() async {
  final isActive = await para.isSessionActive().future;
  if (isActive) {
    // Navigate to authenticated part of your app
  } else {
    await para.logout().future; // Clear any lingering data
    // Navigate to login screen
  }
}
```

2. **Handle App Lifecycle Changes**: Flutter apps can be backgrounded and foregrounded, which may affect session status.

```dart theme={null}
import 'package:flutter/material.dart';
import 'package:para/para.dart';

class YourWidget extends StatefulWidget {
  @override
  _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // App came to foreground, check session
      checkSession();
    }
  }

  Future<void> checkSession() async {
    final isActive = await para.isSessionActive().future;
    if (!isActive) {
      await para.logout().future;
      // Navigate to login screen
    }
  }

  @override
  Widget build(BuildContext context) {
    // Your widget implementation
    return Container();
  }
}
```

## Next Steps

Explore more advanced features and integrations with Para in Flutter:

<CardGroup cols={2}>
  <Card horizontal title="Social Login" imgUrl="/images/v3/custom-ui-social.png" href="/v3/flutter/guides/social-login" description="Learn how to implement social login in Flutter" />

  <Card horizontal title="Pregen Wallets" imgUrl="/images/v3/feature-pregeneration.png" href="/v3/flutter/guides/pregen" description="Create pregenerated wallets for your Flutter app" />
</CardGroup>
