FloatingIcon 加入拖动的动画,以及自动吸附

This commit is contained in:
2025-09-17 18:07:38 +08:00
parent 33aef48f84
commit 922818f39f
7 changed files with 546 additions and 186 deletions

View File

@@ -8,8 +8,15 @@ import '../widgets/gradient_background.dart';
class PartScreen extends StatefulWidget {
final VoidCallback? onHide;
final Offset floatingIconPosition;
final double iconSize;
const PartScreen({super.key, this.onHide});
const PartScreen({
super.key,
this.onHide,
required this.floatingIconPosition,
required this.iconSize,
});
@override
State<PartScreen> createState() => _PartScreenState();
@@ -58,6 +65,45 @@ class _PartScreenState extends State<PartScreen> {
);
}
// 计算PartScreen的位置使其显示在FloatingIcon附近
EdgeInsets _calculatePosition(BoxConstraints constraints) {
final screenWidth = constraints.maxWidth;
final screenHeight = constraints.maxHeight;
final iconX = screenWidth - widget.floatingIconPosition.dx;
final iconY = screenHeight - widget.floatingIconPosition.dy;
// 聊天框的尺寸
final chatWidth = screenWidth * 0.94;
final maxChatHeight = screenHeight * 0.4;
// 判断FloatingIcon在屏幕的哪一边
final isOnRightSide = iconX < screenWidth / 2;
// 计算水平位置
double leftPadding;
if (isOnRightSide) {
// 图标在右边,聊天框显示在左边
leftPadding = (screenWidth - chatWidth) * 0.1;
} else {
// 图标在左边,聊天框显示在右边
leftPadding = screenWidth - chatWidth - (screenWidth - chatWidth) * 0.1;
}
// 计算垂直位置,确保聊天框在图标上方
double bottomPadding = iconY + widget.iconSize + 20;
// 确保聊天框不会超出屏幕
final minBottomPadding = screenHeight * 0.15;
final maxBottomPadding = screenHeight - maxChatHeight - 50;
bottomPadding = bottomPadding.clamp(minBottomPadding, maxBottomPadding);
return EdgeInsets.only(
left: leftPadding,
right: screenWidth - leftPadding - chatWidth,
bottom: bottomPadding,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -67,9 +113,12 @@ class _PartScreenState extends State<PartScreen> {
if (!_isInitialized) {
return const SizedBox.shrink();
}
final position = _calculatePosition(constraints);
final double minHeight = constraints.maxHeight * 0.16;
final double maxHeight = constraints.maxHeight * 0.4;
final double chatWidth = constraints.maxWidth * 0.94;
return Stack(
children: [
Positioned.fill(
@@ -92,71 +141,81 @@ class _PartScreenState extends State<PartScreen> {
),
),
),
Padding(
padding: EdgeInsets.only(bottom: constraints.maxHeight * 0.22),
child: Align(
alignment: Alignment.bottomCenter,
child: Consumer<MessageService>(
builder: (context, messageService, child) {
final messageCount = messageService.messages.length;
if (messageCount > _lastMessageCount) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToBottom();
});
}
_lastMessageCount = messageCount;
return Container(
width: chatWidth,
constraints: BoxConstraints(
minHeight: minHeight,
maxHeight: maxHeight,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
child: GradientBackground(
colors: const [
Color(0XBF3B0A3F),
Color(0xBF0E0E24),
Color(0xBF0C0B33),
],
borderRadius: BorderRadius.circular(6),
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(
top: 50, left: 6, right: 6, bottom: 30),
child: LayoutBuilder(
builder: (context, boxConstraints) {
return ChatBox(
scrollController: _scrollController,
messages: messageService.messages,
);
}),
),
Positioned(
top: 6,
right: 6,
child: IconButton(
icon: Image.asset(
'assets/images/open_in_full.png',
width: 24,
height: 24,
package: 'ai_chat_assistant',
Positioned(
left: position.left,
right: position.right,
bottom: position.bottom,
child: Consumer<MessageService>(
builder: (context, messageService, child) {
final messageCount = messageService.messages.length;
if (messageCount > _lastMessageCount) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToBottom();
});
}
_lastMessageCount = messageCount;
return TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0.8, end: 1.0),
duration: const Duration(milliseconds: 200),
curve: Curves.easeOutBack,
builder: (context, scale, child) {
return Transform.scale(
scale: scale,
child: Container(
width: chatWidth,
constraints: BoxConstraints(
minHeight: minHeight,
maxHeight: maxHeight,
),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
child: GradientBackground(
colors: const [
Color(0XBF3B0A3F),
Color(0xBF0E0E24),
Color(0xBF0C0B33),
],
borderRadius: BorderRadius.circular(6),
child: Stack(
children: [
Padding(
padding: const EdgeInsets.only(
top: 50, left: 6, right: 6, bottom: 30),
child: LayoutBuilder(
builder: (context, boxConstraints) {
return ChatBox(
scrollController: _scrollController,
messages: messageService.messages,
);
}),
),
onPressed: _openFullScreen,
padding: EdgeInsets.zero,
),
Positioned(
top: 6,
right: 6,
child: IconButton(
icon: Image.asset(
'assets/images/open_in_full.png',
width: 24,
height: 24,
package: 'ai_chat_assistant',
),
onPressed: _openFullScreen,
padding: EdgeInsets.zero,
),
),
],
),
],
),
),
),
),
),
);
},
),
);
},
);
},
),
),
],

View File

@@ -135,7 +135,9 @@ class _ChatFooterState extends State<ChatFooter>
Padding(
padding: const EdgeInsets.only(bottom: 12, right: 16),
child: GestureDetector(
onTap: () {},
onTap: () {
},
child: Image.asset(
'assets/images/keyboard_mini.png',package: 'ai_chat_assistant',
width: 24,

View File

@@ -4,7 +4,7 @@ import '../services/message_service.dart';
import '../screens/full_screen.dart';
import '../screens/part_screen.dart';
import 'floating_icon_with_wave.dart';
import 'dart:async'; // 添加此行
import 'dart:async';
import 'package:basic_intl/intl.dart';
class FloatingIcon extends StatefulWidget {
@@ -14,15 +14,25 @@ class FloatingIcon extends StatefulWidget {
State<FloatingIcon> createState() => _FloatingIconState();
}
class _FloatingIconState extends State<FloatingIcon>
with SingleTickerProviderStateMixin {
class _FloatingIconState extends State<FloatingIcon> with TickerProviderStateMixin {
Offset _position = const Offset(10, 120);
final iconSize = 80.0;
bool _isShowPartScreen = false;
bool _isDragging = false;
bool _isAnimating = false;
Offset _targetPosition = const Offset(10, 120);
// 水波纹动画控制器
late AnimationController _waveAnimationController;
// PartScreen 显示动画控制器
late AnimationController _partScreenAnimationController;
// 图片切换定时器
Timer? _imageTimer;
// 添加长按状态标记
bool _isLongPressing = false;
// 新增:图片切换相关
// 图片切换相关
int _imageIndex = 0;
late final List<String> _iconImages = [
'assets/images/ai1_hd.png',
@@ -33,7 +43,6 @@ class _FloatingIconState extends State<FloatingIcon>
'assets/images/ai1_hd_en.png',
'assets/images/ai0_hd_en.png',
];
Timer? _imageTimer; // 用于定时切换图片
@override
void initState() {
@@ -42,18 +51,28 @@ class _FloatingIconState extends State<FloatingIcon>
duration: const Duration(milliseconds: 1000),
vsync: this,
);
// 使用Timer.periodic定时切换图片
// PartScreen动画控制器
_partScreenAnimationController = AnimationController(
duration: const Duration(milliseconds: 250),
vsync: this,
);
// 图片切换定时器
_imageTimer = Timer.periodic(const Duration(seconds: 3), (timer) {
setState(() {
_imageIndex = (_imageIndex + 1) % _iconImages.length;
});
if (mounted && !_isDragging) {
setState(() {
_imageIndex = (_imageIndex + 1) % _iconImages.length;
});
}
});
}
@override
void dispose() {
_waveAnimationController.dispose();
_imageTimer?.cancel(); // 释放Timer
_partScreenAnimationController.dispose();
_imageTimer?.cancel();
super.dispose();
}
@@ -61,14 +80,20 @@ class _FloatingIconState extends State<FloatingIcon>
setState(() {
_isShowPartScreen = true;
});
_partScreenAnimationController.forward();
}
void _hidePartScreen() {
setState(() {
_isShowPartScreen = false;
_partScreenAnimationController.reverse().then((_) {
if (mounted) {
setState(() {
_isShowPartScreen = false;
});
}
});
}
// 显示全屏界面
void _showFullScreen() async {
_hidePartScreen();
await Navigator.of(context).push(
@@ -78,50 +103,106 @@ class _FloatingIconState extends State<FloatingIcon>
);
}
// 更新位置
void _updatePosition(Offset delta) {
if (!_isDragging) return;
setState(() {
final screenSize = MediaQuery.of(context).size;
double newX =
(_position.dx - delta.dx).clamp(0.0, screenSize.width - iconSize);
double newY =
(_position.dy - delta.dy).clamp(0.0, screenSize.height - iconSize);
double newX = (_position.dx - delta.dx).clamp(0.0, screenSize.width - iconSize);
double newY = (_position.dy - delta.dy).clamp(0.0, screenSize.height - iconSize);
_position = Offset(newX, newY);
});
}
// 吸附到屏幕边缘
void _snapToEdge() {
final screenSize = MediaQuery.of(context).size;
final centerX = screenSize.width / 2;
// 判断应该吸到左边还是右边
final shouldSnapToLeft = _position.dx < centerX - iconSize / 2;
final targetX = shouldSnapToLeft ? 0.0 : screenSize.width - iconSize;
setState(() {
_targetPosition = Offset(targetX, _position.dy);
_isAnimating = true;
});
// 使用定时器在动画完成后更新状态
Timer(const Duration(milliseconds: 100), () {
if (mounted) {
setState(() {
_position = _targetPosition;
_isAnimating = false;
});
}
});
}
void _onPanStart(DragStartDetails details) {
_isDragging = true;
_waveAnimationController.stop();
}
void _onPanEnd(DragEndDetails details) {
_isDragging = false;
_snapToEdge();
}
@override
Widget build(BuildContext context) {
// 奇怪的代码不应该放在build里面
// WidgetsBinding.instance.addPostFrameCallback((_) {
// if (messageService.isRecording) {
// if (!_waveAnimationController.isAnimating) {
// _waveAnimationController.repeat();
// }
// } else {
// if (_waveAnimationController.isAnimating) {
// _waveAnimationController.stop();
// }
// }
// });
return Stack(
children: [
if (_isShowPartScreen)
PartScreen(
onHide: _hidePartScreen,
FadeTransition(
opacity: _partScreenAnimationController,
child: SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, 0.3),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _partScreenAnimationController,
curve: Curves.easeOutQuart,
)),
child: PartScreen(
onHide: _hidePartScreen,
floatingIconPosition: _position,
iconSize: iconSize,
)),
),
Positioned(
bottom: _position.dy,
right: _position.dx,
AnimatedPositioned(
duration: const Duration(milliseconds: 250),
curve: Curves.easeOutBack,
bottom: _isAnimating ? _targetPosition.dy : _position.dy,
right: _isAnimating ? _targetPosition.dx : _position.dx,
child: Consumer<MessageService>(
builder: (context, messageService, child) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (messageService.isRecording) {
if (!_waveAnimationController.isAnimating) {
_waveAnimationController.repeat();
}
} else {
if (_waveAnimationController.isAnimating) {
_waveAnimationController.stop();
}
}
});
return GestureDetector(
onTap: _showFullScreen,
onLongPress: () async {
debugPrint('Long press');
_isLongPressing = true; // 标记开始长按
_showPartScreen();
_waveAnimationController.repeat();
await messageService.startVoiceInput();
},
onLongPressUp: () async {
debugPrint('Long press up');
_isLongPressing = false; // 清除长按标记
_waveAnimationController.stop();
await messageService.stopAndProcessVoiceInput();
final hasMessage = messageService.messages.isNotEmpty;
@@ -129,23 +210,49 @@ class _FloatingIconState extends State<FloatingIcon>
_hidePartScreen();
}
},
onPanUpdate: (details) => _updatePosition(details.delta),
child: messageService.isRecording
? FloatingIconWithWave(
animationController: _waveAnimationController,
iconSize: iconSize,
waveColor: Colors.white,
)
: Image.asset(
Intl.getCurrentLocale().startsWith('zh')
? _iconImages[_imageIndex]:_iconImagesEn[_imageIndex],
width: iconSize,
height: iconSize,package: 'ai_chat_assistant',
),
onLongPressEnd: (d) {
debugPrint('Long press end $d');
_isLongPressing = false; // 清除长按标记
},
onPanStart: (details) {
// 只有在非长按状态下才允许拖拽
if (!_isLongPressing) {
_onPanStart(details);
}
},
onPanUpdate: (details) {
// 只有在拖拽状态下才更新位置
if (_isDragging && !_isLongPressing) {
_updatePosition(details.delta);
}
},
onPanEnd: (details) {
if (!_isLongPressing) {
_onPanEnd(details);
}
},
child: AnimatedScale(
scale: _isDragging ? 1.1 : 1.0,
duration: const Duration(milliseconds: 150),
child: messageService.isRecording
? FloatingIconWithWave(
animationController: _waveAnimationController,
iconSize: iconSize,
waveColor: Colors.white,
)
: Image.asset(
Intl.getCurrentLocale().startsWith('zh')
? _iconImages[_imageIndex]
: _iconImagesEn[_imageIndex],
width: iconSize,
height: iconSize,
package: 'ai_chat_assistant',
),
),
);
},
),
),
)
],
);
}