Flutter里玩AI绘图和代码生成,我的租房办公桌快成实验室了
Tech大数据
2026-08-02 20:39
阅读 764
起因与架构设计
产品经理要求在App里加“AI壁纸生成”功能。Flutter生态没有直接对接Midjourney的SDK,因为它跑在Discord上。整体思路:Flutter发送prompt到自建Node.js后端,后端通过Discord API与Midjourney Bot交互,轮询获取结果后返回。
后端核心实现
后端用Node.js和discord.js库,模拟用户在频道发消息。Discord限流严格,需用消息队列控制频率。
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});
client.on('messageCreate', async (message) => {
if (message.author.bot && message.attachments.size > 0) {
const imageUrl = message.attachments.first().url;
io.emit('image_generated', { url: imageUrl, prompt: message.content });
}
});
CodeGeeX辅助后端开发
作为Vim党,我使用CodeGeeX的Vim插件辅助写不擅长的Node.js。写注释即可生成代码,例如消息队列管理器:
// 创建一个消息队列,控制发送频率,每秒最多发送2条消息
class MessageQueue {
constructor(rateLimit = 2) {
this.queue = [];
this.processing = false;
this.rateLimit = rateLimit;
this.lastSentTime = 0;
}
async add(message) {
return new Promise((resolve, reject) => {
this.queue.push({ message, resolve, reject });
this.process();
});
}
async process() {
if (this.processing) return;
this.processing = true;
while (this.queue.length > 0) {
const now = Date.now();
const timeSinceLastSent = now - this.lastSentTime;
if (timeSinceLastSent < 1000 / this.rateLimit) {
await new Promise(r => setTimeout(r, 1000 / this.rateLimit - timeSinceLastSent));
}
const { message, resolve } = this.queue.shift();
try {
await this.sendMessage(message);
this.lastSentTime = Date.now();
resolve();
} catch (error) { reject(error); }
}
this.processing = false;
}
}
注意:注释需清晰,模糊注释(如“图片缓存策略”)可能生成将图片存MongoDB的错误代码,改为“使用Redis缓存图片URL,设置24小时过期”即可。
Flutter端关键实现
Flutter通过WebSocket连接后端,用StreamBuilder处理异步流程,需包含等待、错误和加载状态。
StreamBuilder<String>(
stream: imageService.imageStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Column(children: [
Lottie.asset('assets/loading_animation.json'),
Text('AI正在创作中...'),
]);
}
if (snapshot.hasError) return ErrorWidget(snapshot.error.toString());
if (snapshot.hasData) {
return ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.network(snapshot.data!, fit: BoxFit.cover, loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
return Shimmer.fromColors(baseColor: Colors.grey[300]!, highlightColor: Colors.grey[100]!, child: Container(color: Colors.white));
}),
);
}
return SizedBox.shrink();
},
)
CodeGeeX优化与性能处理
CodeGeeX也支持Flutter,如生成弹性动画代码,使用Curves.elasticOut。性能上,Midjourney生成4K图片过大,采用后端生成缩略图、前端用cached_network_image缓存原图的策略,缓存大小调至50MB平衡体验与存储。
CachedNetworkImage(
imageUrl: thumbnailUrl,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
)
总结
项目耗时两周上线,通过Discord Bot间接调用Midjourney可行。CodeGeeX减少约30%编码时间,但需人工review以防安全漏洞(如硬编码密钥)。功能上线后日生成数百张图片,已开始规划AI头像功能。
标签:MidjourneyCodeGeeX
为你推荐
暂无相关推荐

评论 0