flutter_backend_sdk 1.0.0 copy "flutter_backend_sdk: ^1.0.0" to clipboard
flutter_backend_sdk: ^1.0.0 copied to clipboard

Flutter SDK for Backend Go API - 用户管理、文件存储、好友系统和实时聊天功能的完整SDK

example/main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Backend SDK Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ChatScreen(),
    );
  }
}

class ChatScreen extends StatefulWidget {
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  late BackendSdkClient sdk;
  final TextEditingController _messageController = TextEditingController();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final List<ChatMessage> _messages = [];
  bool _isLoggedIn = false;
  bool _isConnected = false;
  String? _currentRoomId;

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

  void _initializeSDK() {
    sdk = BackendSdkClient(
      baseUrl: 'http://localhost:8080/api/v1',
      wsUrl: 'ws://localhost:8080/ws',
      enableLogging: true,
    );
  }

  Future<void> _login() async {
    try {
      final response = await sdk.auth.login(
        username: _usernameController.text,
        password: _passwordController.text,
      );
      
      sdk.setAccessToken(response.accessToken);
      
      setState(() {
        _isLoggedIn = true;
      });
      
      _showSnackBar('登录成功: ${response.user.username}');
      
      // 连接聊天
      await _connectChat(response.accessToken);
      
    } catch (e) {
      _showSnackBar('登录失败: $e');
    }
  }

  Future<void> _connectChat(String accessToken) async {
    try {
      await sdk.connectChat(accessToken);
      
      // 监听消息
      sdk.chat.messageStream.listen((message) {
        setState(() {
          _messages.add(message);
        });
      });
      
      // 监听连接状态
      sdk.chat.connectionStream.listen((status) {
        setState(() {
          _isConnected = status == ChatConnectionStatus.connected;
        });
        
        if (status == ChatConnectionStatus.connected) {
          _showSnackBar('聊天连接成功');
        } else if (status == ChatConnectionStatus.disconnected) {
          _showSnackBar('聊天连接断开');
        }
      });
      
      // 监听在线状态
      sdk.chat.presenceStream.listen((status) {
        _showSnackBar('用户 ${status.userId} 状态: ${status.status.value}');
      });
      
      // 监听输入状态
      sdk.chat.typingStream.listen((typing) {
        if (typing.isTyping) {
          _showSnackBar('用户 ${typing.userId} 正在输入...');
        }
      });
      
    } catch (e) {
      _showSnackBar('聊天连接失败: $e');
    }
  }

  Future<void> _sendMessage() async {
    if (_messageController.text.isEmpty || _currentRoomId == null) return;
    
    try {
      await sdk.chat.sendTextMessage(_currentRoomId!, _messageController.text);
      _messageController.clear();
    } catch (e) {
      _showSnackBar('发送消息失败: $e');
    }
  }

  Future<void> _createChatRoom() async {
    try {
      // 这里应该选择一个好友ID,为了演示使用固定值
      const friendId = 'friend_user_id';
      final room = await sdk.chatRoom.getOrCreateRoom(friendId);
      
      setState(() {
        _currentRoomId = room.id;
      });
      
      _showSnackBar('聊天房间创建成功: ${room.id}');
    } catch (e) {
      _showSnackBar('创建聊天房间失败: $e');
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  void dispose() {
    sdk.dispose();
    _messageController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Backend SDK Demo'),
        actions: [
          if (_isLoggedIn)
            IconButton(
              icon: Icon(_isConnected ? Icons.wifi : Icons.wifi_off),
              onPressed: null,
            ),
        ],
      ),
      body: _isLoggedIn ? _buildChatInterface() : _buildLoginInterface(),
    );
  }

  Widget _buildLoginInterface() {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextField(
            controller: _usernameController,
            decoration: InputDecoration(
              labelText: '用户名',
              border: OutlineInputBorder(),
            ),
          ),
          SizedBox(height: 16),
          TextField(
            controller: _passwordController,
            decoration: InputDecoration(
              labelText: '密码',
              border: OutlineInputBorder(),
            ),
            obscureText: true,
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _login,
            child: Text('登录'),
          ),
        ],
      ),
    );
  }

  Widget _buildChatInterface() {
    return Column(
      children: [
        // 状态栏
        Container(
          padding: EdgeInsets.all(8.0),
          color: Colors.grey[200],
          child: Row(
            children: [
              Text('连接状态: ${_isConnected ? "已连接" : "未连接"}'),
              Spacer(),
              if (_currentRoomId == null)
                ElevatedButton(
                  onPressed: _createChatRoom,
                  child: Text('创建聊天房间'),
                ),
              if (_currentRoomId != null)
                Text('房间: ${_currentRoomId!.substring(0, 8)}...'),
            ],
          ),
        ),
        // 消息列表
        Expanded(
          child: ListView.builder(
            itemCount: _messages.length,
            itemBuilder: (context, index) {
              final message = _messages[index];
              return ListTile(
                title: Text(message.content),
                subtitle: Text('${message.fromUserId} - ${message.timestamp}'),
                trailing: Text(message.type.value),
              );
            },
          ),
        ),
        // 输入框
        if (_currentRoomId != null)
          Container(
            padding: EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    decoration: InputDecoration(
                      hintText: '输入消息...',
                      border: OutlineInputBorder(),
                    ),
                    onSubmitted: (_) => _sendMessage(),
                  ),
                ),
                SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _isConnected ? _sendMessage : null,
                  child: Text('发送'),
                ),
              ],
            ),
          ),
      ],
    );
  }
}

// 演示其他功能的示例
class SDKDemoFunctions {
  late BackendSdkClient sdk;

  SDKDemoFunctions() {
    sdk = BackendSdkClient(
      baseUrl: 'http://localhost:8080/api/v1',
      enableLogging: true,
    );
  }

  // 用户注册示例
  Future<void> registerExample() async {
    try {
      await sdk.auth.register(RegisterRequest(
        username: 'testuser',
        email: 'test@example.com',
        password: 'password123',
        verificationCode: '123456',
      ));
      print('注册成功');
    } catch (e) {
      print('注册失败: $e');
    }
  }

  // 文件上传示例
  Future<void> fileUploadExample() async {
    try {
      final file = await sdk.file.uploadFile(
        '/path/to/file.jpg',
        request: FileUploadRequest(
          category: 'images',
          isPublic: false,
        ),
      );
      print('文件上传成功: ${file.filename}');
    } catch (e) {
      print('文件上传失败: $e');
    }
  }

  // 好友系统示例
  Future<void> friendSystemExample() async {
    try {
      // 发送好友请求
      await sdk.friend.createFriendRequest(
        CreateFriendRequestRequest(
          receiverId: 'user_id',
          note: '你好,我想加你为好友',
        ),
      );

      // 获取好友请求
      final requests = await sdk.friend.getIncomingRequests();
      print('收到 ${requests.items.length} 个好友请求');

      // 获取好友列表
      final friends = await sdk.friend.getFriends();
      print('好友数量: ${friends.items.length}');
    } catch (e) {
      print('好友系统操作失败: $e');
    }
  }
}
0
likes
125
points
27
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Flutter SDK for Backend Go API - 用户管理、文件存储、好友系统和实时聊天功能的完整SDK

Homepage

License

MIT (license)

Dependencies

crypto, flutter, http, mime, path, shared_preferences, web_socket_channel

More

Packages that depend on flutter_backend_sdk