61 lines
1.6 KiB
Dart
61 lines
1.6 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
/// 全局 Navigator key,供不依赖页面 context 的 toast 等场景使用
|
|
final GlobalKey<NavigatorState> appNavigatorKey = GlobalKey<NavigatorState>();
|
|
|
|
OverlayEntry? _entry;
|
|
Timer? _timer;
|
|
|
|
/// 屏幕正中央的 toast,展示时长按文字长度分档:≤8 字 2 秒,≤20 字 3 秒,更长 4 秒
|
|
void showToast(String msg) {
|
|
_timer?.cancel();
|
|
_entry?.remove();
|
|
_entry = null;
|
|
|
|
final overlay = appNavigatorKey.currentState?.overlay;
|
|
if (overlay == null) return;
|
|
|
|
final entry = OverlayEntry(
|
|
builder: (_) => Positioned.fill(
|
|
child: IgnorePointer(
|
|
child: Center(
|
|
child: Container(
|
|
constraints: const BoxConstraints(maxWidth: 280),
|
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
|
decoration: BoxDecoration(
|
|
color: Colors.black.withValues(alpha: 0.78),
|
|
borderRadius: BorderRadius.circular(8),
|
|
),
|
|
child: Text(
|
|
msg,
|
|
textAlign: TextAlign.center,
|
|
style: const TextStyle(
|
|
color: Colors.white,
|
|
fontSize: 14,
|
|
height: 1.4,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
overlay.insert(entry);
|
|
_entry = entry;
|
|
_timer = Timer(_durationFor(msg), () {
|
|
if (_entry == entry) {
|
|
entry.remove();
|
|
_entry = null;
|
|
}
|
|
});
|
|
}
|
|
|
|
Duration _durationFor(String msg) {
|
|
final len = msg.length;
|
|
if (len <= 8) return const Duration(seconds: 2);
|
|
if (len <= 20) return const Duration(seconds: 3);
|
|
return const Duration(seconds: 4);
|
|
}
|