首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >基于Flutter3.32+DeepSeek电脑端AI流式对话程序

基于Flutter3.32+DeepSeek电脑端AI流式对话程序

原创
作者头像
andy2018
发布2025-06-07 11:20:36
发布2025-06-07 11:20:36
2631
举报
文章被收录于专栏:h5h5

原创实战客户端ai模板,flutter3.32+getx+dio+markdown调用deepseek搭建桌面版ai项目。

flutter3-winseek支持侧边栏收缩/展开、上下文多轮对话、代码高亮、本地存储会话、代码块横向滚动、复制代码功能、图片100%宽度渲染、在线图片预览、网络链接跳转、表格功能

flutter-winseek采用自定义无边框窗口、系统托盘图标。

技术栈

  • 技术框架:flutter3.32.0+dart3.8.0
  • 对话大模型:deepseek-v3
  • 流请求:dio^5.8.0+1
  • 窗口管理:window_manager^0.5.0
  • 托盘管理:system_tray^2.0.3
  • 路由/状态管理:get^4.7.2
  • 存储服务:get_storage^2.1.1
  • markdown解析:flutter_markdown^0.7.7
  • 高亮组件:flutter_highlight^0.7.0
  • 环境变量配置:flutter_dotenv^5.2.1

项目框架结构

采用最新版Flutter3.32搭建项目框架,接入DeepSeek大模型。

项目入口配置main.dart

代码语言:actionscript
复制
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_manager/window_manager.dart';

import 'controller/app.dart';
import 'controller/chat.dart';

// 引入路由配置
import 'router/index.dart';

void main() async {
  // 初始化存储服务
  await GetStorage.init();

  // 将.env文件内容加载到dotenv中
  await dotenv.load(fileName: '.env');

  // 注册GetxController
  Get.put(AppStore());
  Get.put(ChatStore());

  // 初始化window_manager窗口
  WidgetsFlutterBinding.ensureInitialized();
  await windowManager.ensureInitialized();
  WindowOptions windowOptions = WindowOptions(
    size: Size(850, 620),
    center: true,
    backgroundColor: Colors.transparent,
    skipTaskbar: false,
    titleBarStyle: TitleBarStyle.hidden
  );
  windowManager.waitUntilReadyToShow(windowOptions, () async {
    windowManager.setAsFrameless();
    windowManager.setHasShadow(true);
    await windowManager.show();
    await windowManager.focus();
  });

  // 初始化托盘
  initSystemTray();

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    // 获取AppStore实例
    final appStore = AppStore.to;

    return GetMaterialApp(
      title: 'FLUTTER3 WINSEEK',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Color(0xFF4F6BFE)),
        useMaterial3: true,
        fontFamily: Platform.isWindows ? 'Microsoft YaHei' : null,
      ),
      // 初始路由
      initialRoute: appStore.isLogin ? '/' : '/login',
      // 路由页面
      getPages: routePages,
      // 初始弹窗key
      navigatorKey: MyDialog.navigatorKey,
      localizationsDelegates: [
        // Add your ShirneDialogLocalizations delegate here
        ShirneDialogLocalizations.delegate,
      ],
    );
  }
}

// 创建系统托盘图标
Future<void> initSystemTray() async {
  String trayIco = 'assets/images/tray.ico';
  SystemTray systemTray = SystemTray();

  // 初始化系统托盘
  await systemTray.initSystemTray(
    title: 'system-tray',
    iconPath: trayIco,
  );

  // 右键菜单
  final Menu menu = Menu();
  await menu.buildFrom([
    MenuItemLabel(label: '打开主界面', image: 'assets/images/tray.ico', onClicked: (menuItem) async => await windowManager.show()),
    MenuItemLabel(label: '隐藏窗口', image: 'assets/images/tray.ico', onClicked: (menuItem) async => await windowManager.hide()),
    MenuItemLabel(label: '设置中心', image: 'assets/images/tray.ico', onClicked: (menuItem) => Get.toNamed('/setting')),
    MenuItemLabel(label: '锁屏', image: 'assets/images/tray.ico', onClicked: (menuItem) => {}),
    MenuItemLabel(label: '关闭程序并退出', image: 'assets/images/tray.ico', onClicked: (menuItem) async => await windowManager.destroy()),
  ]);
  await systemTray.setContextMenu(menu);

  // 右键事件
  systemTray.registerSystemTrayEventHandler((eventName) async {
    debugPrint('eventName: $eventName');
    if (eventName == kSystemTrayEventClick) {
      Platform.isWindows ? await windowManager.show() : systemTray.popUpContextMenu();
    } else if (eventName == kSystemTrayEventRightClick) {
      Platform.isWindows ? systemTray.popUpContextMenu() : await windowManager.show();
    }
  });
}

项目环境变量配置.env

代码语言:actionscript
复制
# 项目名称
APP_NAME = 'Flutter3-WinSeek'

# DeepSeek API配置
DEEPSEEK_API_KEY = apikey
DEEPSEEK_BASE_URL = https://api.deepseek.com

在页面中获取配置好的环境变量。

代码语言:actionscript
复制
// 获取.env环境变量baseUrl和apiKey
String baseURL = dotenv.get('DEEPSEEK_BASE_URL');
String apiKEY = dotenv.get('DEEPSEEK_API_KEY');

项目通用布局

代码语言:actionscript
复制
return Scaffold(
  backgroundColor: Colors.grey[50],
  body: DragToResizeArea(
    child: Row(
      children: [
        // 侧边栏
        AnimatedSize(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          child: Container(
            width: collapsed ? 0 : 260,
            decoration: BoxDecoration(
              border: Border(right: BorderSide(color: Colors.grey.withAlpha(50)))
            ),
            child: Material(
              color: Color(0xFFF3F3F3),
              child: Sidebar(),
            ),
          ),
        ),
        // 主体容器
        Expanded(
          child: Column(
            children: [
              // 自定义导航栏
              SizedBox(
                height: 30.0,
                child: Row(
                  children: [
                    IconButton(
                      onPressed: () {
                        setState(() {
                          collapsed = !collapsed;
                        });
                      },
                      icon: Icon(collapsed ? Icons.format_indent_increase : Icons.format_indent_decrease, size: 16.0,),
                      tooltip: collapsed ? '展开' : '收缩',
                    ),
                    Expanded(
                      child: DragToMoveArea(
                        child: SizedBox(
                          height: double.infinity,
                        ),
                      ),
                    ),
                    // 右上角操作按钮
                    WinBtns(
                      leading: Row(
                        children: [
                          ...
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              // 右侧主面板
              Expanded(
                child: Container(
                  child: widget.child,
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  ),
);

flutter3编辑框模板

代码语言:actionscript
复制
return Container(
  width: double.infinity,
  padding: EdgeInsets.symmetric(vertical: 10.0),
  child: Column(
    spacing: 6.0,
    children: [
      // 技能栏
      if (widget.skillbar)
      ScrollConfiguration(
        behavior: CustomScrollBehavior(),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          padding: EdgeInsets.symmetric(horizontal: 15.0),
          child: Row(
            spacing: 4.0,
            children: [
              ...
            ]
          ),
        ),
      ),
      // 编辑框
      Container(
        margin: EdgeInsets.symmetric(horizontal: 15.0),
        padding: EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.withAlpha(100), width: .5),
          borderRadius: BorderRadius.circular(15.0),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha(20),
              offset: Offset(0.0, 3.0),
              blurRadius: 6.0,
              spreadRadius: 0.0,
            ),
          ]
        ),
        child: Column(
          spacing: 10.0,
          children: [
            // 输入框
            ConstrainedBox(
              constraints: BoxConstraints(minHeight: 48.0, maxHeight: 150.0),
              child: TextField(
                ...
              ),
            ),
            // 操作栏
            Row(
              spacing: 10.0,
              children: [
                SizedBox(
                  height: 30.0,
                  child: TextButton(
                    onPressed: () {
                      setState(() {
                        isDeep =! isDeep;
                      });
                    },
                    style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(isDeep ? Color(0xFF4F6BFE).withAlpha(30) : Colors.grey[200]),
                      padding: WidgetStateProperty.all(EdgeInsets.symmetric(horizontal: 10.0)),
                    ),
                    child: Row(
                      spacing: 4.0,
                      children: [
                        Icon(Icons.stream, color: isDeep ? Color(0xFF4F6BFE) : Colors.black, size: 18.0,),
                        Text('深度思考(R1)', style: TextStyle(color: isDeep ? Color(0xFF4F6BFE) : Colors.black, fontSize: 13.0),),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 30.0,
                  child: TextButton(
                    onPressed: () {
                      setState(() {
                        isNetwork =! isNetwork;
                      });
                    },
                    style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(isNetwork ? Color(0xFF4F6BFE).withAlpha(30) : Colors.grey[200]),
                      padding: WidgetStateProperty.all(EdgeInsets.symmetric(horizontal: 10.0)),
                    ),
                    child: Row(
                      spacing: 4.0,
                      children: [
                        Icon(Icons.travel_explore, color: isNetwork ? Color(0xFF4F6BFE) : Colors.black, size: 18.0,),
                        Text('联网', style: TextStyle(color: isNetwork ? Color(0xFF4F6BFE) : Colors.black, fontSize: 13.0),),
                      ],
                    ),
                  ),
                ),
                Spacer(),
                SizedBox(
                  height: 30.0,
                  width: 30.0,
                  child: PopupMenuButton(
                    icon: Icon(Icons.add),
                    padding: EdgeInsets.zero,
                    tooltip: '',
                    offset: Offset(-35.0, 0),
                    constraints: BoxConstraints(maxWidth: 160),
                    color: Colors.white,
                    itemBuilder: (BuildContext context) {
                      return [
                        PopupMenuItem(value: 'camera', height: 40.0, child: Row(spacing: 5.0, children: [Icon(Icons.camera_alt_outlined), Text('拍照识文字')],)),
                        PopupMenuItem(value: 'image', height: 40.0, child: Row(spacing: 5.0, children: [Icon(Icons.image_outlined), Text('图片识文字')],)),
                        PopupMenuItem(value: 'file', height: 40.0, child: Row(spacing: 5.0, children: [Icon(Icons.file_present_outlined), Text('文件')],)),
                      ];
                    },
                    onSelected: (value) {
                      debugPrint(value);
                    },
                  ),
                ),
                SizedBox(
                  height: 30.0,
                  width: 30.0,
                  child: IconButton(
                    onPressed: disabled ? null : () => handleSubmit(),
                    icon: loading ?
                      SizedBox(height: 16.0, width: 16.0, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.0,))
                      :
                      Icon(Icons.send, color: Colors.white, size: 18.0)
                    ,
                    style: ButtonStyle(
                      backgroundColor: WidgetStateProperty.all(disabled ? Color(0xFF4F6BFE).withAlpha(100) : Color(0xFF4F6BFE)),
                      padding: WidgetStateProperty.all(EdgeInsets.zero)
                    ),
                    disabledColor: Colors.red,
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    ],
  )
);

flutter3调用deepseek流式输出

通过dio插件来请求deepseek api接口,实现流式对话功能。

代码语言:actionscript
复制
final response = await dio.post(
  '$baseURL/v1/chat/completions',
  options: Options(
    // 响应超时
    receiveTimeout: const Duration(seconds: 60),
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer $apiKEY",
    },
    // 设置响应类型为流式响应
    responseType: ResponseType.stream,
  ),
  data: {
    // 多轮会话
    'messages': widget.multiConversation ? chatStore.historySession : [{'role': 'user', 'content': editorValue}],
    'model': 'deepseek-chat', // deepseek-chat对话模型 deepseek-reasoner推理模型
    'stream': true, // 流式输出
    'max_tokens': 8192, // 限制一次请求中模型生成 completion 的最大 token 数(默认使用 4096)
    'temperature': 0.4, // 严谨采样 越低越严谨(默认1)
  }
);

基于uniapp+deepseek+vue3跨平台ai流式对话:https://cloud.tencent.com/developer/article/2518214

electron35+deepseek桌面端ai模板:https://cloud.tencent.com/developer/article/2514843

vue3.5+deepseek网页版ai流式对话:https://cloud.tencent.com/developer/article/2508594

DeepSeek-Vue3基于vite6+vant4仿deepseek/Kimi流式AI聊天小助手

flutter3.27+getx仿抖音app短视频商城:https://cloud.tencent.com/developer/article/2493971

Electron32桌面端os系统:https://cloud.tencent.com/developer/article/2449406

electron31+vue3客户端聊天Exe实例:https://cloud.tencent.com/developer/article/2435159

tauri2.0+vue3客户端admin后台系统:https://cloud.tencent.com/developer/article/2458392

uniapp+vue3仿携程预订客房模板:https://cloud.tencent.com/developer/article/2474766

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 技术栈
  • 项目框架结构
  • 项目入口配置main.dart
  • 项目环境变量配置.env
  • 项目通用布局
  • flutter3编辑框模板
  • flutter3调用deepseek流式输出
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档