Compare commits

..

5 Commits
dev ... master

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

@ -1,9 +1,12 @@
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import '../common_widget/Song_widegt.dart'; import '../common_widget/Song_widegt.dart';
import '../models/MusicsListBean.dart';
import '../models/getMusicList_bean.dart'; import '../models/getMusicList_bean.dart';
import '../models/getRank_bean.dart'; import '../models/getRank_bean.dart';
const String _getMusicList = "http://8.210.250.29:10010/musics/three-random";
const String _getMusic = 'http://8.210.250.29:10010/musics/';
const String _getMusic1 = 'http://8.210.250.29:10010/musics/1'; const String _getMusic1 = 'http://8.210.250.29:10010/musics/1';
const String _getMusic2 = 'http://8.210.250.29:10010/musics/2'; const String _getMusic2 = 'http://8.210.250.29:10010/musics/2';
const String _getMusic3 = 'http://8.210.250.29:10010/musics/3'; const String _getMusic3 = 'http://8.210.250.29:10010/musics/3';
@ -13,6 +16,34 @@ const String _getSongDetail = 'http://8.210.250.29:10010/musics';
class GetMusic { class GetMusic {
final Dio dio = Dio(); final Dio dio = Dio();
Future<MusicsListBean> getMusicList({required String Authorization}) async {
Response response = await dio.get(
_getMusicList,
data: {
'Authorization': Authorization,
},
options: Options(headers: {
'Authorization': Authorization,
'Content-Type': 'application/json;charset=UTF-8'
}));
return MusicsListBean.fromMap(response.data);
}
Future<MusicListBean> getMusicById({required int id, required String Authorization}) async {
print(_getMusic + id.toString());
Response response = await dio.get(
_getMusic + id.toString(),
data: {
'Authorization': Authorization,
},
options: Options(headers: {
'Authorization': Authorization,
'Content-Type': 'application/json;charset=UTF-8'
}));
print(response.data);
return MusicListBean.formMap(response.data);
}
Future<MusicListBean> getMusic1({required String Authorization}) async { Future<MusicListBean> getMusic1({required String Authorization}) async {
Response response = await dio.get( Response response = await dio.get(
_getMusic1, _getMusic1,
@ -26,6 +57,7 @@ class GetMusic {
print(response.data); print(response.data);
return MusicListBean.formMap(response.data); return MusicListBean.formMap(response.data);
} }
Future<MusicListBean> getMusic2({required String Authorization}) async { Future<MusicListBean> getMusic2({required String Authorization}) async {
Response response = await dio.get( Response response = await dio.get(
_getMusic2, _getMusic2,

@ -42,7 +42,7 @@ class commentMusic {
_postComment, _postComment,
data: { data: {
'content': content, 'content': content,
'MusicId': musicId, 'musicId': musicId,
'Authorization':Authorization 'Authorization':Authorization
}, },
@ -57,9 +57,9 @@ class commentMusic {
class getCommentApi { class getCommentApi {
final Dio dio = Dio(); final Dio dio = Dio();
Future<GetCommentBean> getComment({ Future<GetCommentBean> getComment({
required String musicId, required int musicId,
required String pageNo, required int pageNo,
required String pageSize, required int pageSize,
required String Authorization, required String Authorization,
}) async { }) async {
Response response = await dio.get( Response response = await dio.get(

@ -0,0 +1,201 @@
// audio_player_controller.dart
import 'dart:async';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import '../common_widget/Song_widegt.dart';
import '../models/getMusicList_bean.dart';
import '../common/download_manager.dart';
import '../common_widget/app_data.dart';
import '../api/api_music_list.dart';
class AudioPlayerController extends GetxController {
final audioPlayer = AudioPlayer();
final downloadManager = Get.find<DownloadManager>();
final appData = AppData();
// Observable values
final currentSongIndex = 0.obs;
final duration = Duration.zero.obs;
final position = Duration.zero.obs;
final isPlaying = false.obs;
final isLoading = false.obs;
final isRotating = false.obs;
final isDisposed = false.obs;
// Current song info
final artistName = ''.obs;
final musicName = ''.obs;
final likesStatus = false.obs;
final collectionsStatus = false.obs;
// Song lists
final songList = <Song>[].obs;
final ids = <int>[].obs;
final songUrls = <String>[].obs;
final artists = <String>[].obs;
final musicNames = <String>[].obs;
final likes = <bool>[].obs;
final collections = <bool>[].obs;
StreamSubscription? _positionSubscription;
StreamSubscription? _durationSubscription;
StreamSubscription? _playerStateSubscription;
void initWithSongs(List<Song> songs, int initialIndex) {
songList.value = songs;
currentSongIndex.value = initialIndex;
_initializeSongLists();
_initializePlayer();
}
void _initializeSongLists() {
for (int i = 0; i < songList.length; i++) {
ids.add(songList[i].id);
songUrls.add(songList[i].musicurl ?? '');
artists.add(songList[i].artist);
musicNames.add(songList[i].title);
likes.add(songList[i].likes ?? false);
collections.add(songList[i].collection ?? false);
}
_updateCurrentSongInfo();
}
void _initializePlayer() {
// Position updates
_positionSubscription = audioPlayer.positionStream.listen((pos) {
position.value = pos;
});
// Duration updates
_durationSubscription = audioPlayer.durationStream.listen((dur) {
duration.value = dur ?? Duration.zero;
});
// Player state updates
_playerStateSubscription = audioPlayer.playerStateStream.listen((state) {
// isPlaying.value = state.playing;
if (state.processingState == ProcessingState.completed) {
playNext();
}
});
// Initial load
_loadAndPlayCurrentSong();
}
void _updateCurrentSongInfo() {
artistName.value = artists[currentSongIndex.value];
musicName.value = musicNames[currentSongIndex.value];
likesStatus.value = likes[currentSongIndex.value];
collectionsStatus.value = collections[currentSongIndex.value];
}
Future<void> toggleLike() async {
final currentIndex = currentSongIndex.value;
likesStatus.value = !likesStatus.value;
likes[currentIndex] = likesStatus.value;
}
Future<void> toggleCollection() async {
final currentIndex = currentSongIndex.value;
collectionsStatus.value = !collectionsStatus.value;
collections[currentIndex] = collectionsStatus.value;
}
Future<void> _loadAndPlayCurrentSong() async {
isLoading.value = true;
position.value = Duration.zero;
duration.value = Duration.zero;
_updateCurrentSongInfo();
await _checkAndUpdateSongStatus(currentSongIndex.value);
try {
await audioPlayer.stop();
final localSong = downloadManager.getLocalSong(currentSongIndex.value);
final audioSource = localSong != null
? AudioSource.file(localSong.musicurl!)
: AudioSource.uri(Uri.parse(songUrls[currentSongIndex.value]));
await audioPlayer.setAudioSource(audioSource, preload: true);
duration.value = await audioPlayer.duration ?? Duration.zero;
await audioPlayer.play();
} catch (e) {
print('Error loading audio source: $e');
} finally {
isLoading.value = false;
}
}
Future<void> _checkAndUpdateSongStatus(int index) async {
if (songList[index].likes == null || songList[index].collection == null) {
try {
MusicListBean musicListBean = await GetMusic().getMusicById(
id: ids[index],
Authorization: appData.currentToken,
);
if (musicListBean.code == 200) {
likes[index] = musicListBean.likeOrNot!;
collections[index] = musicListBean.collectOrNot!;
if (index == currentSongIndex.value) {
likesStatus.value = musicListBean.likeOrNot!;
collectionsStatus.value = musicListBean.collectOrNot!;
}
}
} catch (e) {
print('Error fetching song status: $e');
}
}
}
void playOrPause() async {
if (audioPlayer.playing) {
isPlaying.value = false;
await audioPlayer.pause();
} else {
await audioPlayer.play();
isPlaying.value = true;
}
}
void playNext() {
if (currentSongIndex.value < songList.length - 1) {
currentSongIndex.value++;
} else {
currentSongIndex.value = 0;
}
_loadAndPlayCurrentSong();
}
void playPrevious() {
if (currentSongIndex.value > 0) {
currentSongIndex.value--;
} else {
currentSongIndex.value = songList.length - 1;
}
_loadAndPlayCurrentSong();
}
void seekTo(Duration position) async {
await audioPlayer.seek(position);
}
void changeSong(int index) {
currentSongIndex.value = index;
_loadAndPlayCurrentSong();
}
@override
void onClose() {
isDisposed.value = true;
_positionSubscription?.cancel();
_durationSubscription?.cancel();
_playerStateSubscription?.cancel();
audioPlayer.dispose();
super.onClose();
}
}

@ -121,7 +121,7 @@ class DownloadManager extends GetxController {
bool removeSong(int id) { bool removeSong(int id) {
if (_downloads[id.toString()]?.isCompleted ?? false) { if (_downloads[id.toString()]?.isCompleted ?? false) {
File file = File.fromUri(Uri.parse(_downloads[id.toString()]!.song.musicurl)); File file = File.fromUri(Uri.parse(_downloads[id.toString()]!.song.musicurl!));
file.deleteSync(); file.deleteSync();
_downloads.remove(id.toString()); _downloads.remove(id.toString());
_saveDownloadsToPrefs(); _saveDownloadsToPrefs();
@ -156,7 +156,7 @@ class DownloadManager extends GetxController {
try { try {
final filePath = await downloadApi.downloadMusic( final filePath = await downloadApi.downloadMusic(
musicUrl: song.musicurl, musicUrl: song.musicurl!,
name: fileName, name: fileName,
context: context, context: context,
onProgress: (progress) { onProgress: (progress) {
@ -169,7 +169,7 @@ class DownloadManager extends GetxController {
downloadItem.isCompleted = true; downloadItem.isCompleted = true;
downloadItem.isDownloading = false; downloadItem.isDownloading = false;
downloadItem.progress = 1.0; downloadItem.progress = 1.0;
song.musicurl = _getLocalAudioPath(fileName, song.musicurl); song.musicurl = _getLocalAudioPath(fileName, song.musicurl!);
print(song.musicurl); print(song.musicurl);
} else { } else {
downloadItem.isDownloading = false; downloadItem.isDownloading = false;

@ -3,10 +3,10 @@ class Song {
String artistPic; String artistPic;
String title; String title;
String artist; String artist;
String musicurl; String? musicurl;
int id; int id;
bool likes; bool? likes;
bool collection; bool? collection;
// //
Song({ Song({

@ -7,5 +7,7 @@ class AppData extends GetxController{
String get currentToken => box.read('currentToken'); String get currentToken => box.read('currentToken');
String get currentUsername => box.read('currentUsername') ?? '游客'; String get currentUsername => box.read('currentUsername') ?? '游客';
String get currentAvatar=> box.read('currentAvatar') ?? 'http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg'; String get currentAvatar=> box.read('currentAvatar') ?? 'http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg';
set currentToken(String token) => box.write('currentToken', token);
set currentUsername(String username) => box.write('currentUsername', username);
set currentAvatar(String avatar) => box.write('currentAvatar', avatar);
} }

@ -0,0 +1,35 @@
class MusicsListBean {
int? code;
String? msg;
List<MusicItem>? data;
MusicsListBean.fromMap(Map map) {
code = map['code'];
msg = map['msg'];
if (map['data'] != null && map['data'] is List) {
data = (map['data'] as List).map((item) => MusicItem.fromMap(item)).toList();
}
}
}
class MusicItem {
int? id;
String? name;
String? coverPath;
String? musicPath;
String? singerName;
String? uploadUserName;
bool? likeOrNot;
bool? collectOrNot;
MusicItem.fromMap(Map map) {
id = map['id'];
name = map['name'];
coverPath = map['coverPath'];
musicPath = map['musicPath'];
singerName = map['singerName'];
uploadUserName = map['uploadUserName'];
likeOrNot = map['likeOrNot'];
collectOrNot = map['collectOrNot'];
}
}

@ -24,8 +24,6 @@ class DataBean {
String? musicPath; String? musicPath;
String? name; String? name;
DataBean._formMap(Map map) { DataBean._formMap(Map map) {
id = map['id']; id = map['id'];
singerName = map['singerName']; singerName = map['singerName'];

@ -17,17 +17,22 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
@override @override
void initState() { void initState() {
tabController = TabController( tabController = TabController(initialIndex: 0, length: 2, vsync: this);
initialIndex: 0, tabController.addListener(() {
length: 2, if (!tabController.indexIsChanging) {
vsync: this FocusScope.of(context).unfocus();
); }
});
super.initState(); super.initState();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
image: DecorationImage( image: DecorationImage(
image: AssetImage("assets/img/app_bg.png"), image: AssetImage("assets/img/app_bg.png"),
@ -45,7 +50,8 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
children: [ children: [
// //
Padding( Padding(
padding: const EdgeInsets.only(top: 110, left: 40, right: 40), padding:
const EdgeInsets.only(top: 110, left: 40, right: 40),
child: Row( child: Row(
children: [ children: [
const Column( const Column(
@ -55,8 +61,7 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 20, fontSize: 20,
fontWeight: FontWeight.w500 fontWeight: FontWeight.w500),
),
), ),
Row( Row(
children: [ children: [
@ -65,16 +70,14 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 20, fontSize: 20,
fontWeight: FontWeight.w500 fontWeight: FontWeight.w500),
),
), ),
Text( Text(
"喵听", "喵听",
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 32, fontSize: 32,
fontWeight: FontWeight.w800 fontWeight: FontWeight.w800),
),
), ),
], ],
), ),
@ -102,12 +105,14 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
child: TabBar( child: TabBar(
controller: tabController, controller: tabController,
unselectedLabelColor: const Color(0xffCDCDCD), unselectedLabelColor: const Color(0xffCDCDCD),
// onTap: (_) {
// FocusScope.of(context).unfocus();
// },
labelColor: Colors.black, labelColor: Colors.black,
indicatorSize: TabBarIndicatorSize.tab, indicatorSize: TabBarIndicatorSize.tab,
indicator: BoxDecoration( indicator: BoxDecoration(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
color: MColor.LGreen color: MColor.LGreen),
),
tabs: [ tabs: [
Container( Container(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
@ -150,6 +155,6 @@ class _BeginViewState extends State<BeginView> with TickerProviderStateMixin {
), ),
), ),
), ),
); ));
} }
} }

@ -27,6 +27,16 @@ class _LoginVState extends State<LoginV> {
IconData iconPassword = CupertinoIcons.eye_fill; IconData iconPassword = CupertinoIcons.eye_fill;
bool obscurePassword = true; bool obscurePassword = true;
final _passwordFocusNode = FocusNode();
final _nameFocusNode = FocusNode();
@override
void dispose() {
_passwordFocusNode.dispose();
_nameFocusNode.dispose();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Form( return Form(
@ -39,6 +49,7 @@ class _LoginVState extends State<LoginV> {
child: MyTextField( child: MyTextField(
controller: nameController, controller: nameController,
hintText: '请输入账号', hintText: '请输入账号',
focusNode: _nameFocusNode,
obscureText: false, obscureText: false,
keyboardType: TextInputType.emailAddress, keyboardType: TextInputType.emailAddress,
prefixIcon: Image.asset("assets/img/login_user.png"))), prefixIcon: Image.asset("assets/img/login_user.png"))),
@ -49,6 +60,7 @@ class _LoginVState extends State<LoginV> {
child: MyTextField( child: MyTextField(
controller: passwordController, controller: passwordController,
hintText: '请输入密码', hintText: '请输入密码',
focusNode: _passwordFocusNode,
obscureText: obscurePassword, obscureText: obscurePassword,
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
prefixIcon: Image.asset("assets/img/login_lock.png"), prefixIcon: Image.asset("assets/img/login_lock.png"),
@ -78,9 +90,12 @@ class _LoginVState extends State<LoginV> {
child: TextButton( child: TextButton(
onPressed: () async { onPressed: () async {
try { try {
_nameFocusNode.unfocus();
_passwordFocusNode.unfocus();
Get.dialog( Get.dialog(
Center( Center(
child: CircularProgressIndicator( child: CircularProgressIndicator(
color: const Color(0xff429482),
backgroundColor: Colors.grey[200], backgroundColor: Colors.grey[200],
), ),
), ),
@ -98,11 +113,10 @@ class _LoginVState extends State<LoginV> {
SnackBar( SnackBar(
content: const Center( content: const Center(
child: Text( child: Text(
'登录成功!', '登录成功',
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 16.0, // fontSize: 16.0, //
fontWeight: FontWeight.w500, //
), ),
), ),
), ),
@ -110,7 +124,8 @@ class _LoginVState extends State<LoginV> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, backgroundColor: Colors.white,
elevation: 3, elevation: 3,
width: 200, // width: 200,
//
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),
@ -120,7 +135,6 @@ class _LoginVState extends State<LoginV> {
.getInfo( .getInfo(
Authorization: AppData().currentToken); Authorization: AppData().currentToken);
} else { } else {
Get.back();
throw Exception("账号或密码错误"); throw Exception("账号或密码错误");
} }
} catch (error) { } catch (error) {
@ -130,11 +144,10 @@ class _LoginVState extends State<LoginV> {
SnackBar( SnackBar(
content: Center( content: Center(
child: Text( child: Text(
'${error.toString().replaceAll ('Exception: ', '')} ', error.toString().replaceAll ('Exception: ', ''),
style: TextStyle( style: const TextStyle(
color: Colors.red, color: Colors.black,
fontSize: 16.0, // fontSize: 16.0, //
fontWeight: FontWeight.w500, //
), ),
), ),
), ),
@ -142,7 +155,11 @@ class _LoginVState extends State<LoginV> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, backgroundColor: Colors.white,
elevation: 3, elevation: 3,
width: 200, // margin: EdgeInsets.only(
bottom: 50, // 50
right: (MediaQuery.of(context).size.width - 200) / 2, //
left: (MediaQuery.of(context).size.width - 200) / 2,
),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),

@ -30,6 +30,12 @@ class _SignUpViewState extends State<SignUpView> {
bool obscurePassword = true; bool obscurePassword = true;
bool signUpRequired = false; bool signUpRequired = false;
final _nameFocusNode = FocusNode();
final _passwordFocusNode = FocusNode();
final _emailFocusNode = FocusNode();
final _confirmPSWFocusNode = FocusNode();
final _confirmFocusNode = FocusNode();
// //
Timer? _timer; Timer? _timer;
int _countDown = 60; int _countDown = 60;
@ -75,6 +81,7 @@ class _SignUpViewState extends State<SignUpView> {
child: MyTextField( child: MyTextField(
controller: nameController, controller: nameController,
hintText: '请输入用户名', hintText: '请输入用户名',
focusNode: _nameFocusNode,
obscureText: false, obscureText: false,
keyboardType: TextInputType.emailAddress, keyboardType: TextInputType.emailAddress,
prefixIcon: Image.asset("assets/img/login_user.png"), prefixIcon: Image.asset("assets/img/login_user.png"),
@ -94,6 +101,7 @@ class _SignUpViewState extends State<SignUpView> {
controller: emailController, controller: emailController,
hintText: '请输入邮箱名', hintText: '请输入邮箱名',
obscureText: false, obscureText: false,
focusNode: _emailFocusNode,
keyboardType: TextInputType.name, keyboardType: TextInputType.name,
prefixIcon: Image.asset("assets/img/setup_email.png"), prefixIcon: Image.asset("assets/img/setup_email.png"),
validator: (val) { validator: (val) {
@ -110,6 +118,7 @@ class _SignUpViewState extends State<SignUpView> {
controller: passwordController, controller: passwordController,
hintText: '请输入密码', hintText: '请输入密码',
obscureText: obscurePassword, obscureText: obscurePassword,
focusNode: _passwordFocusNode,
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
prefixIcon: Image.asset("assets/img/login_lock.png"), prefixIcon: Image.asset("assets/img/login_lock.png"),
suffixIcon: IconButton( suffixIcon: IconButton(
@ -144,6 +153,7 @@ class _SignUpViewState extends State<SignUpView> {
controller: confirmPSWController, controller: confirmPSWController,
hintText: '请确认密码', hintText: '请确认密码',
obscureText: obscurePassword, obscureText: obscurePassword,
focusNode: _confirmPSWFocusNode,
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
prefixIcon: Image.asset("assets/img/login_lock.png"), prefixIcon: Image.asset("assets/img/login_lock.png"),
suffixIcon: IconButton( suffixIcon: IconButton(
@ -184,6 +194,7 @@ class _SignUpViewState extends State<SignUpView> {
controller: confirmController, controller: confirmController,
hintText: '请输入验证码', hintText: '请输入验证码',
obscureText: false, obscureText: false,
focusNode: _confirmFocusNode,
keyboardType: TextInputType.name, keyboardType: TextInputType.name,
prefixIcon: Image.asset("assets/img/setup_confirm.png"), prefixIcon: Image.asset("assets/img/setup_confirm.png"),
validator: (val) { validator: (val) {
@ -205,6 +216,11 @@ class _SignUpViewState extends State<SignUpView> {
), ),
onPressed: _canSendCode onPressed: _canSendCode
? () async { ? () async {
_nameFocusNode.unfocus();
_emailFocusNode.unfocus();
_passwordFocusNode.unfocus();
_confirmPSWFocusNode.unfocus();
_confirmFocusNode.unfocus();
UniversalBean bean = await SetupApiClient().verification( UniversalBean bean = await SetupApiClient().verification(
email: emailController.text, email: emailController.text,
); );
@ -213,9 +229,9 @@ class _SignUpViewState extends State<SignUpView> {
startTimer(); // startTimer(); //
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Center( content: const Center(
child: Text( child: Text(
'验证码已成功发送!', '验证码发送成功',
style: TextStyle(color: Colors.black), style: TextStyle(color: Colors.black),
), ),
), ),
@ -223,7 +239,11 @@ class _SignUpViewState extends State<SignUpView> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, backgroundColor: Colors.white,
elevation: 3, elevation: 3,
width: 200, margin: EdgeInsets.only(
bottom: 50, // 50
right: (MediaQuery.of(context).size.width - 200) / 2, //
left: (MediaQuery.of(context).size.width - 200) / 2,
),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),
@ -232,13 +252,12 @@ class _SignUpViewState extends State<SignUpView> {
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Center( content: const Center(
child: Text( child: Text(
'邮箱为空或格式不正确!', '请检查邮箱',
style: TextStyle( style: TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 16.0, // fontSize: 16.0, //
fontWeight: FontWeight.w500, //
), ),
), ),
), ),
@ -246,7 +265,12 @@ class _SignUpViewState extends State<SignUpView> {
behavior: SnackBarBehavior.floating, behavior: SnackBarBehavior.floating,
backgroundColor: Colors.white, backgroundColor: Colors.white,
elevation: 3, elevation: 3,
width: 220, // width: 220,
margin: EdgeInsets.only(
bottom: 50, // 50
right: (MediaQuery.of(context).size.width - 200) / 2, //
left: (MediaQuery.of(context).size.width - 200) / 2,
),
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
), ),
@ -271,6 +295,11 @@ class _SignUpViewState extends State<SignUpView> {
width: MediaQuery.of(context).size.width * 0.85, width: MediaQuery.of(context).size.width * 0.85,
child: TextButton( child: TextButton(
onPressed: () async { onPressed: () async {
_nameFocusNode.unfocus();
_emailFocusNode.unfocus();
_passwordFocusNode.unfocus();
_confirmPSWFocusNode.unfocus();
_confirmFocusNode.unfocus();
if (_formKey.currentState?.validate() == false) { if (_formKey.currentState?.validate() == false) {
const Text( const Text(
'', '',

@ -1,329 +0,0 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_player_miao/api/api_music_return.dart';
import 'package:music_player_miao/common_widget/app_data.dart';
import 'package:music_player_miao/models/getComment_bean.dart';
import 'package:music_player_miao/models/universal_bean.dart';
import 'package:music_player_miao/widget/text_field.dart';
class CommentView extends StatefulWidget {
@override
_CommentViewState createState() => _CommentViewState();
CommentView({super.key, required this.initialSongIndex});
late final int initialSongIndex;
}
class _CommentViewState extends State<CommentView> {
List comments = [];
TextEditingController commentController = TextEditingController();
FocusNode commentFocusNode = FocusNode();
List commentTimes = [];
List commentHeader = [];
List commentName = [];
bool ascendingOrder = true;
int playlistCount = 0;
@override
void initState() {
super.initState();
_fetchSonglistData();
}
Future<void> _fetchSonglistData() async {
try {
GetCommentBean bean1 = await getCommentApi().getComment(
musicId: '1',
pageNo: '0',
pageSize: '10',
Authorization: AppData().currentToken,
);
// rows
if (bean1.rows == null) {
print('No comments found');
return;
}
setState(() {
comments = bean1.rows!.map((rows) => rows.content ?? 'No content').toList();
commentTimes = bean1.rows!.map((rows) => rows.time ?? 'Unknown time').toList();
commentHeader = bean1.rows!.map((rows) => rows.avatar ?? 'Default avatar').toList();
commentName = bean1.rows!.map((rows) => rows.username ?? 'Anonymous').toList();
playlistCount = comments.length;
});
} catch (error) {
print('Error fetching songlist data: $error');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
// backgroundColor: Colors.transparent,
appBar: AppBar(
centerTitle: true,
backgroundColor: const Color(0xffF6FFD1),
title: const Text(
'评论(200)',
style: TextStyle(
color: Colors.black,
fontSize: 22
),
),
elevation: 0,
leading: IconButton(
onPressed: () {
Get.back();
},
icon: Image.asset(
"assets/img/back.png",
width: 25,
height: 25,
fit: BoxFit.contain,
),
),
),
body: Column(
children: [
Container(
height: 80,
padding: const EdgeInsets.only(left: 20, right: 10),
decoration: BoxDecoration(
color: const Color(0xffF9F2AF),
borderRadius: BorderRadius.circular(20)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset(
"assets/img/artist_pic.png",
width: 60,
height: 60,
fit: BoxFit.cover,
),
),
const SizedBox(width: 20,),
const Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"背对背拥抱",
maxLines: 1,
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
),
Text(
"林俊杰",
maxLines: 1,
style: TextStyle(color: Colors.black, fontSize: 14),
)
],
),
],
),
IconButton(
onPressed: () {},
icon: Image.asset(
"assets/img/music_pause.png",
width: 25,
height: 25,
fit: BoxFit.contain,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
"评论区",
style: TextStyle(
fontSize: 18
),
),
Row(
children: [
const Text(
"时间",
style: TextStyle(
fontSize: 16
),
),
IconButton(
onPressed: () {
setState(() {
ascendingOrder = !ascendingOrder;
// 使
List<int> sortedIndexes = List<int>.generate(comments.length, (i) => i);
sortedIndexes.sort((a, b) {
DateTime timeA = DateTime.parse(commentTimes[a]);
DateTime timeB = DateTime.parse(commentTimes[b]);
return ascendingOrder ? timeA.compareTo(timeB) : timeB.compareTo(timeA);
});
comments = [for (var i in sortedIndexes) comments[i]];
commentTimes = [for (var i in sortedIndexes) commentTimes[i]];
commentHeader = [for (var i in sortedIndexes) commentHeader[i]];
commentName = [for (var i in sortedIndexes) commentName[i]];
});
},
icon: Image.asset(
ascendingOrder
? "assets/img/commend_up.png"
: "assets/img/commend_down.png",
fit: BoxFit.contain,
),
),
],
)
],
),
),
///
Expanded(
child:
ListView.builder(
itemCount: comments.length,
itemBuilder: (context, index) {
return ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
backgroundImage: NetworkImage(commentHeader[index])
),
const SizedBox(width: 10,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(commentName[index],
style: const TextStyle(fontSize: 18)),
const SizedBox(width: 8),
// Adjust the spacing between elements
Text(commentTimes[index],
style: const TextStyle(fontSize: 14),),
// Add the timestamp
],
),
],
), // Ad
Padding(
padding: const EdgeInsets.only(
left: 50, top: 10, bottom: 20),
child: Text(
comments[index],
style: const TextStyle(
fontSize: 18), // Customize the font size if needed
),
),
Container(
width: 560,
height: 2,
color: const Color(0xffE3F0ED),
)
],
),
);
},
),
),
///
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextFieldColor(
controller: commentController,
hintText: '来发表你的评论吧!',
)
),
const SizedBox(width: 8.0),
ElevatedButton(
onPressed: () async {
submitComment();
UniversalBean bean = await commentMusic().comment(
musicId: widget.initialSongIndex,
content: commentController.text,
Authorization: AppData().currentToken);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xff429482),
// Change Colors.blue to your desired background color
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
10), // Adjust the radius as needed
),
minimumSize: const Size(30, 44),
),
child: const Text(
'提交',
style: TextStyle(
fontSize: 16
),
),
),
],
),
),
],
),
);
}
void submitComment() async {
String comment = commentController.text.trim();
if (comment.isEmpty) {
print('Comment cannot be empty');
Get.snackbar('错误', '评论不能为空');
return;
}
print('Submitting comment with content: $comment');
try {
UniversalBean bean = await commentMusic().comment(
musicId: widget.initialSongIndex,
content: comment,
Authorization: AppData().currentToken,
);
//
if (bean.code == 200) {
print('Comment submitted successfully');
commentController.clear();
_fetchSonglistData(); //
} else {
print('Failed to submit comment: ${bean.msg}');
Get.snackbar('错误', bean.msg ?? '评论提交失败');
}
} catch (error) {
print('Error submitting comment: $error');
}
}
}

@ -0,0 +1,436 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_player_miao/api/api_music_return.dart';
import 'package:music_player_miao/common_widget/app_data.dart';
import 'package:music_player_miao/models/getComment_bean.dart';
import 'package:music_player_miao/models/universal_bean.dart';
import 'package:music_player_miao/widget/text_field.dart';
class CommentView extends StatefulWidget {
final int id;
final String song;
final String singer;
final String cover;
const CommentView({
super.key,
required this.id,
required this.song,
required this.singer,
required this.cover,
});
@override
_CommentViewState createState() => _CommentViewState();
}
class _CommentViewState extends State<CommentView> {
List comments = [];
ScrollController _scrollController = ScrollController();
TextEditingController commentController = TextEditingController();
FocusNode commentFocusNode = FocusNode();
List commentTimes = [];
List commentHeader = [];
List commentName = [];
bool ascendingOrder = true;
int _page = 1;
int _pageSize = 10;
int _total = 0;
bool _isLoading = false;
bool _hasMoreData = true;
bool _isSendingComment = false;
String avatar = AppData().currentAvatar;
String username = AppData().currentUsername;
bool _isInitialLoading = true;
@override
void initState() {
super.initState();
_scrollController.addListener(_scrollListener);
_fetchCommentData();
commentController.addListener(() {
setState(() {});
});
}
@override
void dispose() {
_scrollController.dispose();
commentController.dispose();
super.dispose();
}
void _scrollListener() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if (!_isLoading && _hasMoreData) {
_loadMoreData();
}
}
}
Future<void> _loadMoreData() async {
if (_isLoading || !_hasMoreData) return;
setState(() {
_isLoading = true;
});
_page++;
await _fetchCommentData();
setState(() {
_isLoading = false;
});
}
String formatDateTime(String dateTimeStr) {
try {
DateTime dateTime = DateTime.parse(dateTimeStr);
//
return "${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}";
} catch (e) {
return dateTimeStr; //
}
}
Future<void> _fetchCommentData() async {
print('Fetching page $_page');
try {
GetCommentBean bean1 = await getCommentApi().getComment(
musicId: widget.id,
pageNo: _page,
pageSize: _pageSize,
Authorization: AppData().currentToken,
);
if (bean1.rows == null || bean1.rows!.isEmpty) {
setState(() {
_hasMoreData = false;
_isInitialLoading = false;
});
return;
}
_total = bean1.total!;
setState(() {
if (_page == 1) {
comments =
bean1.rows!.map((rows) => rows.content ?? 'No content').toList();
commentTimes = bean1.rows!
.map((rows) => formatDateTime(rows.time ?? 'Unknown time'))
.toList();
commentHeader = bean1.rows!
.map((rows) => rows.avatar ?? 'Default avatar')
.toList();
commentName =
bean1.rows!.map((rows) => rows.username ?? 'Anonymous').toList();
} else {
comments.addAll(
bean1.rows!.map((rows) => rows.content ?? 'No content').toList());
commentTimes.addAll(bean1.rows!
.map((rows) => formatDateTime(rows.time ?? 'Unknown time'))
.toList());
commentHeader.addAll(bean1.rows!
.map((rows) => rows.avatar ?? 'Default avatar')
.toList());
commentName.addAll(
bean1.rows!.map((rows) => rows.username ?? 'Anonymous').toList());
}
_hasMoreData = comments.length < _total;
_isInitialLoading = false;
});
} catch (error) {
print('Error fetching comment data: $error');
setState(() {
_isLoading = false;
_isInitialLoading = false;
});
}
}
void _sortComments() {
setState(() {
comments = comments.reversed.toList();
commentTimes = commentTimes.reversed.toList();
commentHeader = commentHeader.reversed.toList();
commentName = commentName.reversed.toList();
});
}
//
bool isCommentValid() {
String comment = commentController.text.trim();
return comment.isNotEmpty;
}
void submitComment() async {
String comment = commentController.text.trim();
if (!isCommentValid()) {
return; //
}
setState(() {
_isSendingComment = true;
});
try {
UniversalBean bean = await commentMusic().comment(
musicId: widget.id,
content: comment,
Authorization: AppData().currentToken,
);
if (bean.code == 200) {
commentController.clear();
setState(() {
comments = [comment, ...comments];
commentTimes = [
formatDateTime(DateTime.now().toString()),
...commentTimes
];
commentHeader = [avatar, ...commentHeader];
commentName = [username, ...commentName];
_total++;
});
}
} catch (error) {
print('Error submitting comment: $error');
} finally {
setState(() {
_isSendingComment = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
backgroundColor: const Color(0xffF6FFD1),
title: Text(
'评论($_total)',
style: TextStyle(color: Colors.black, fontSize: 22),
),
elevation: 0,
leading: IconButton(
onPressed: () {
Get.back();
},
icon: Image.asset(
"assets/img/back.png",
width: 25,
height: 25,
fit: BoxFit.contain,
),
),
),
body: Column(
children: [
// ... ...
Container(
height: 80,
padding: const EdgeInsets.only(left: 20, right: 10),
decoration: BoxDecoration(
color: const Color(0xffF9F2AF),
borderRadius: BorderRadius.circular(20)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
widget.cover,
width: 60,
height: 60,
fit: BoxFit.cover,
),
),
const SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
widget.song,
maxLines: 1,
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
),
Text(
widget.singer,
maxLines: 1,
style: const TextStyle(
color: Colors.black, fontSize: 14),
)
],
),
],
),
],
),
),
//
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
"评论区",
style: TextStyle(fontSize: 18),
),
Row(
children: [
const Text(
"时间",
style: TextStyle(fontSize: 16),
),
IconButton(
onPressed: () {
setState(() {
ascendingOrder = !ascendingOrder;
_sortComments();
});
},
icon: Image.asset(
ascendingOrder
? "assets/img/commend_up.png"
: "assets/img/commend_down.png",
fit: BoxFit.contain,
),
),
],
)
],
),
),
//
Expanded(
child: _isInitialLoading
? const Center(
child: CircularProgressIndicator(
color: Color(0xff429482),
),
)
: ListView.builder(
controller: _scrollController,
itemCount: comments.length + 1, // +1
itemBuilder: (context, index) {
if (index == comments.length) {
// "没有更多数据"
return Container(
padding: const EdgeInsets.all(16.0),
alignment: Alignment.center,
child: _isLoading
? const CircularProgressIndicator(
color: Color(0xff429482),
)
: _hasMoreData
? const Text('上拉加载更多')
: const Text('没有更多评论了'),
);
}
return ListTile(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
backgroundImage:
NetworkImage(commentHeader[index])),
const SizedBox(width: 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(commentName[index],
style: const TextStyle(fontSize: 18)),
Text(
commentTimes[index],
style: const TextStyle(fontSize: 14),
),
],
),
],
),
Padding(
padding: const EdgeInsets.only(
left: 50, top: 10, bottom: 20),
child: Text(
comments[index],
style: const TextStyle(fontSize: 18),
),
),
Container(
width: 560,
height: 2,
color: const Color(0xffE3F0ED),
)
],
),
);
},
),
),
//
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextFieldColor(
controller: commentController,
hintText: '来发表你的评论吧!',
enabled: !_isSendingComment,
),
),
const SizedBox(width: 8.0),
ElevatedButton(
onPressed: isCommentValid() && !_isSendingComment
? submitComment
: null,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xff429482),
foregroundColor: Colors.black45,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
minimumSize: const Size(30, 44),
disabledBackgroundColor: Colors.grey,
),
child: _isSendingComment
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 2,
),
)
: const Text(
'发送',
style: TextStyle(fontSize: 16),
),
),
],
),
),
],
),
);
}
}

@ -4,13 +4,16 @@ import 'package:get/get.dart';
import 'package:music_player_miao/api/api_music_return.dart'; import 'package:music_player_miao/api/api_music_return.dart';
import 'package:music_player_miao/common_widget/app_data.dart'; import 'package:music_player_miao/common_widget/app_data.dart';
import 'package:music_player_miao/models/search_bean.dart'; import 'package:music_player_miao/models/search_bean.dart';
import 'package:music_player_miao/view/commend_view.dart'; import 'package:music_player_miao/view/comment_view.dart';
import '../../view_model/home_view_model.dart'; import '../../view_model/home_view_model.dart';
import '../api/api_music_likes.dart';
import '../api/api_music_list.dart'; import '../api/api_music_list.dart';
import '../common/download_manager.dart'; import '../common/download_manager.dart';
import '../common_widget/Song_widegt.dart'; import '../common_widget/Song_widegt.dart';
import '../common_widget/list_cell.dart'; import '../common_widget/list_cell.dart';
import '../models/MusicsListBean.dart';
import '../models/getMusicList_bean.dart'; import '../models/getMusicList_bean.dart';
import '../models/universal_bean.dart';
import 'music_view.dart'; import 'music_view.dart';
class HomeView extends StatefulWidget { class HomeView extends StatefulWidget {
@ -20,67 +23,56 @@ class HomeView extends StatefulWidget {
State<HomeView> createState() => _HomeViewState(); State<HomeView> createState() => _HomeViewState();
} }
class _HomeViewState extends State<HomeView> { class _HomeViewState extends State<HomeView>
// 使 GetX HomeViewModel homeVM with AutomaticKeepAliveClientMixin {
// Get.put() HomeViewModel GetX 便使
final homeVM = Get.put(HomeViewModel()); final homeVM = Get.put(HomeViewModel());
// TextEditingController
//
final TextEditingController _controller = TextEditingController(); final TextEditingController _controller = TextEditingController();
// _isSearching
// _isSearching true_isSearching false
bool _isSearching = false; bool _isSearching = false;
final downloadManager = Get.put(DownloadManager()); final downloadManager = Get.put(DownloadManager());
List<Song> selectedSongs = [];
@override
bool get wantKeepAlive => true;
@override
void initState() { void initState() {
super.initState(); super.initState();
_fetchSonglistData(); _fetchSonglistData();
} }
List<Song> selectedSongs = [];
Future<void> _fetchSonglistData() async {
MusicListBean bean1 =
await GetMusic().getMusic1(Authorization: AppData().currentToken);
MusicListBean bean2 =
await GetMusic().getMusic2(Authorization: AppData().currentToken);
MusicListBean bean3 =
await GetMusic().getMusic3(Authorization: AppData().currentToken);
Future<void> _onRefresh() async {
try {
//
await _fetchSonglistData();
} catch (e) {
print('Refresh error: $e');
//
}
}
Future<void> _fetchSonglistData() async {
try {
MusicsListBean bean =
await GetMusic().getMusicList(Authorization: AppData().currentToken);
setState(() { setState(() {
selectedSongs = [ selectedSongs = [];
Song( for (var data in bean.data!) {
artistPic: bean1.coverPath!, selectedSongs.add(Song(
title: bean1.name!, artistPic: data.coverPath!,
artist: bean1.singerName!, title: data.name!,
musicurl: bean1.musicPath!, artist: data.singerName!,
pic: bean1.coverPath!, musicurl: data.musicPath!,
id: bean1.id!, pic: data.coverPath!,
likes: bean1.likeOrNot!, id: data.id!,
collection: bean1.collectOrNot!), likes: data.likeOrNot!,
Song( collection: data.collectOrNot!,
artistPic: bean2.coverPath!, ));
title: bean2.name!, }
artist: bean2.singerName!,
musicurl: bean2.musicPath!,
pic: bean2.coverPath!,
id: bean2.id!,
likes: bean2.likeOrNot!,
collection: bean2.collectOrNot!),
Song(
artistPic: bean3.coverPath!,
title: bean3.name!,
artist: bean3.singerName!,
musicurl: bean3.musicPath!,
pic: bean3.coverPath!,
id: bean3.id!,
likes: bean3.likeOrNot!,
collection: bean3.collectOrNot!),
];
}); });
} catch (e) {
print('Error occurred while fetching song list: $e');
}
} }
/// ///
List<Map> imgList = [ List<Map> imgList = [
@ -107,23 +99,32 @@ class _HomeViewState extends State<HomeView> {
// id // id
for (var data in bean.data!) { for (var data in bean.data!) {
if (data.id != null) { // id null if (data.id != null) {
// id null
// 使 id Future // 使 id Future
songDetailsFutures.add( songDetailsFutures.add(GetMusicDetail()
GetMusicDetail().getMusicDetail( .getMusicDetail(
songId: data.id!, songId: data.id!,
Authorization: AppData().currentToken, Authorization: AppData().currentToken,
).then((details) { )
.then((details) {
if (details != null) { if (details != null) {
// Song // Song
return Song( return Song(
artistPic: details.artistPic ?? '', // artistPic: details.artistPic ?? '',
title: data.name ?? '', // //
artist: details.artist ?? '', // title: data.name ?? '',
musicurl: details.musicurl ?? '', // //
pic: details.pic ?? '', // artist: details.artist ?? '',
id: details.id, // ID //
likes: details.likes, // musicurl: details.musicurl ?? '',
//
pic: details.pic ?? '',
//
id: details.id,
// ID
likes: details.likes,
//
collection: details.collection, // collection: details.collection, //
); );
} }
@ -131,8 +132,7 @@ class _HomeViewState extends State<HomeView> {
}).catchError((error) { }).catchError((error) {
print("Error occurred while fetching song details: $error"); print("Error occurred while fetching song details: $error");
return null; // null return null; // null
}) }));
);
} else { } else {
print("Song ID is null for song: ${data.name}"); print("Song ID is null for song: ${data.name}");
} }
@ -142,7 +142,10 @@ class _HomeViewState extends State<HomeView> {
List<Song?> songDetailsList = await Future.wait(songDetailsFutures); List<Song?> songDetailsList = await Future.wait(songDetailsFutures);
// null // null
List<Song> validSongDetails = songDetailsList.where((song) => song != null).cast<Song>().toList(); List<Song> validSongDetails = songDetailsList
.where((song) => song != null)
.cast<Song>()
.toList();
// UI _filteredData // UI _filteredData
setState(() { setState(() {
@ -175,6 +178,8 @@ class _HomeViewState extends State<HomeView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
/// ///
var MySwiperWidget = Swiper( var MySwiperWidget = Swiper(
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
@ -205,9 +210,7 @@ class _HomeViewState extends State<HomeView> {
child: Scaffold( child: Scaffold(
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,
body: SingleChildScrollView( body: Column(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
/// ///
Container( Container(
@ -217,24 +220,21 @@ class _HomeViewState extends State<HomeView> {
children: [ children: [
Text( Text(
'喵听', '喵听',
style: style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
SizedBox(
width: 10,
), ),
SizedBox(width: 10),
Text( Text(
'你的云端音乐库', '你的云端音乐库',
style: style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
), ),
], ],
), ),
), ),
const SizedBox(height: 10,), const SizedBox(height: 10),
/// ///
Container( Container(
padding: const EdgeInsets.only(left: 20, right: 20, top: 10), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column( child: Column(
children: [ children: [
Container( Container(
@ -305,8 +305,10 @@ class _HomeViewState extends State<HomeView> {
MaterialPageRoute( MaterialPageRoute(
// MusicView // MusicView
builder: (context) => MusicView( builder: (context) => MusicView(
songList: _filteredData, // songList: _filteredData,
initialSongIndex: index, // //
initialSongIndex:
index, //
), ),
), ),
); );
@ -319,18 +321,35 @@ class _HomeViewState extends State<HomeView> {
), ),
), ),
const SizedBox(height: 10,), const SizedBox(
height: 10,
),
///+
Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
color: const Color(0xff429482),
backgroundColor: Colors.white,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
///+ ///+
Container( Container(
padding: const EdgeInsets.only(left: 20, right: 20, top: 10), padding:
const EdgeInsets.only(left: 20, right: 20, top: 10),
child: const Text( child: const Text(
'每日推荐', '每日推荐',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w500),
), ),
), ),
const SizedBox(height: 5,), const SizedBox(height: 5),
Container( Container(
padding: const EdgeInsets.only(left: 20, right: 20, top: 5), padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 5),
height: 186, height: 186,
width: double.infinity, width: double.infinity,
child: MySwiperWidget, child: MySwiperWidget,
@ -341,13 +360,17 @@ class _HomeViewState extends State<HomeView> {
/// ///
Container( Container(
alignment: Alignment.topLeft, alignment: Alignment.topLeft,
padding: const EdgeInsets.only(left: 20, right: 20, top: 5), padding:
const EdgeInsets.only(left: 20, right: 20, top: 5),
child: const Text( child: const Text(
'精选歌曲', '精选歌曲',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500), style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w500),
),
), ),
const SizedBox(
height: 5,
), ),
const SizedBox(height: 5,),
ListView.builder( ListView.builder(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
itemCount: selectedSongs.length, itemCount: selectedSongs.length,
@ -355,20 +378,65 @@ class _HomeViewState extends State<HomeView> {
shrinkWrap: true, shrinkWrap: true,
itemBuilder: (context, index) { itemBuilder: (context, index) {
return ListTile( return ListTile(
leading: Image.network(selectedSongs[index].pic), leading: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
selectedSongs[index].pic,
width: 60,
height: 60,
fit: BoxFit.cover,
),
),
title: Text( title: Text(
selectedSongs[index].title, selectedSongs[index].title,
style: const TextStyle(fontSize: 18, color: Colors.black), style: const TextStyle(
fontSize: 18, color: Colors.black),
), ),
subtitle: Text( subtitle: Text(
selectedSongs[index].artist, selectedSongs[index].artist,
style: const TextStyle(fontSize: 16, color: Colors.black), style: const TextStyle(
fontSize: 16, color: Colors.black),
), ),
trailing: InkWell( trailing: Padding(
onTap: () { padding: const EdgeInsets.only(right: 16),
_bottomSheet(context, index); child: InkWell(
onTap: () async {
setState(() {
selectedSongs[index].likes =
!selectedSongs[index].likes!;
});
UniversalBean response = await LikesApiMusic()
.likesMusic(
musicId: selectedSongs[index].id,
Authorization:
AppData().currentToken);
if (response.code != 200) {
setState(() {
selectedSongs[index].likes =
!selectedSongs[index].likes!;
});
}
}, },
child: Image.asset('assets/img/More.png'), child: selectedSongs[index].likes!
? Image.asset(
'assets/img/like.png',
width: 24,
height: 24,
)
: ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.grey[700]!,
BlendMode.srcIn,
),
child: Image.asset(
'assets/img/unlike.png',
width: 24,
height: 24,
),
),
),
), ),
onTap: () { onTap: () {
Navigator.push( Navigator.push(
@ -377,12 +445,16 @@ class _HomeViewState extends State<HomeView> {
builder: (context) => MusicView( builder: (context) => MusicView(
songList: selectedSongs, songList: selectedSongs,
initialSongIndex: index, initialSongIndex: index,
onSongStatusChanged: (index, isCollected, isLiked) { onSongStatusChanged:
(index, isCollected, isLiked) {
setState(() { setState(() {
// selectedSongs[index].collection =
selectedSongs[index].collection = isCollected; isCollected;
selectedSongs[index].likes = isLiked; selectedSongs[index].likes = isLiked;
downloadManager.updateSongInfo(selectedSongs[index].id, isCollected, isLiked); downloadManager.updateSongInfo(
selectedSongs[index].id,
isCollected,
isLiked);
}); });
}, },
), ),
@ -393,34 +465,15 @@ class _HomeViewState extends State<HomeView> {
}, },
), ),
const SizedBox(height: 10,), const SizedBox(
/// height: 10,
Container( ),
padding: const EdgeInsets.only(left: 20, right: 20, top: 5), ],
child: const Text(
'精选歌单',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
), ),
), ),
const SizedBox(height: 5,),
SizedBox(
height: 180,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
padding: const EdgeInsets.only(left: 20),
itemCount: homeVM.listArr.length,
itemBuilder: (context, index) {
var sObj = homeVM.listArr[index];
return ListRow(
sObj: sObj,
onPressed: () {},
onPressedPlay: () {},
);
}),
), ),
],
), ),
],
), ),
), ),
); );
@ -433,7 +486,8 @@ class _HomeViewState extends State<HomeView> {
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(30)), borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
), ),
builder: (context) => StatefulBuilder( // 使StatefulBuilder便 builder: (context) => StatefulBuilder(
// 使StatefulBuilder便
builder: (context, setState) { builder: (context, setState) {
bool likesnot = false; // bool likesnot = false; //
@ -479,11 +533,11 @@ class _HomeViewState extends State<HomeView> {
Column( Column(
children: [ children: [
IconButton( IconButton(
onPressed: (){}, onPressed: () {},
icon: Image.asset("assets/img/list_good.png"), icon: Image.asset("assets/img/list_good.png"),
iconSize: 60, iconSize: 60,
), ),
Text("点赞") const Text("点赞")
], ],
), ),
Column( Column(
@ -491,9 +545,12 @@ class _HomeViewState extends State<HomeView> {
IconButton( IconButton(
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
Get.to(() => CommentView( // Get.to(() =>
initialSongIndex: index, // CommentView(
)); // id:,
// song:,
// singer:,
// ));
}, },
icon: Image.asset("assets/img/list_comment.png"), icon: Image.asset("assets/img/list_comment.png"),
iconSize: 60, iconSize: 60,

@ -5,6 +5,101 @@ import 'package:music_player_miao/view/user/user_view.dart';
import '../home_view.dart'; import '../home_view.dart';
import '../release_view.dart'; import '../release_view.dart';
//
class MiniPlayer extends StatelessWidget {
const MiniPlayer({super.key});
@override
Widget build(BuildContext context) {
return Container(
height: 50, //
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
blurRadius: 4,
offset: const Offset(0, -1),
),
],
),
child: Row(
children: [
//
Container(
width: 50,
height: 50,
color: Colors.grey[200],
child: Image.asset(
'assets/img/artist_pic.png',
fit: BoxFit.cover,
),
),
//
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'背对背拥抱',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 2),
Text(
'林俊杰',
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
//
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.play_arrow),
onPressed: () {},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
iconSize: 24,
),
const SizedBox(width: 16),
IconButton(
icon: const Icon(Icons.playlist_play),
onPressed: () {},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
iconSize: 24,
),
const SizedBox(width: 8),
],
),
],
),
),
),
],
),
);
}
}
class MainTabView extends StatefulWidget { class MainTabView extends StatefulWidget {
const MainTabView({super.key}); const MainTabView({super.key});
@override @override
@ -38,7 +133,13 @@ class _MainTabViewState extends State<MainTabView> with SingleTickerProviderStat
return Scaffold( return Scaffold(
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
key: scaffoldKey, key: scaffoldKey,
body: TabBarView( body: Stack(
children: [
// TabBarView
Column(
children: [
Expanded(
child: TabBarView(
controller: controller, controller: controller,
children: const [ children: const [
HomeView(), HomeView(),
@ -47,21 +148,33 @@ class _MainTabViewState extends State<MainTabView> with SingleTickerProviderStat
UserView() UserView()
], ],
), ),
bottomNavigationBar: Container( ),
],
),
//
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const MiniPlayer(),
Container(
color: Colors.white, color: Colors.white,
child: TabBar( child: TabBar(
controller: controller, controller: controller,
indicatorColor: Colors.transparent, indicatorColor: Colors.transparent,
labelColor: Colors.black, labelColor: Colors.black,
labelStyle: const TextStyle(fontSize: 12), // labelStyle: const TextStyle(fontSize: 12),
unselectedLabelColor: const Color(0xffCDCDCD), unselectedLabelColor: const Color(0xffCDCDCD),
unselectedLabelStyle: const TextStyle(fontSize: 12), // unselectedLabelStyle: const TextStyle(fontSize: 12),
tabs: [ tabs: [
Tab( Tab(
height: 60, // height: 60,
icon: Image.asset( icon: Image.asset(
selectTab == 0 ? "assets/img/home_tab.png" : "assets/img/home_tab_un.png", selectTab == 0 ? "assets/img/home_tab.png" : "assets/img/home_tab_un.png",
width: 32, // width: 32,
height: 32, height: 32,
), ),
text: "首页", text: "首页",
@ -96,6 +209,11 @@ class _MainTabViewState extends State<MainTabView> with SingleTickerProviderStat
], ],
), ),
), ),
],
),
),
],
),
); );
} }
} }

@ -6,9 +6,11 @@ import 'package:music_player_miao/common_widget/app_data.dart';
import '../../view_model/home_view_model.dart'; import '../../view_model/home_view_model.dart';
import '../api/api_music_likes.dart'; import '../api/api_music_likes.dart';
import '../api/api_collection.dart'; import '../api/api_collection.dart';
import '../api/api_music_list.dart';
import '../common/download_manager.dart'; import '../common/download_manager.dart';
import '../common_widget/Song_widegt.dart'; import '../common_widget/Song_widegt.dart';
import '../view/commend_view.dart'; import '../models/getMusicList_bean.dart';
import '../view/comment_view.dart';
import '../models/universal_bean.dart'; import '../models/universal_bean.dart';
class MusicView extends StatefulWidget { class MusicView extends StatefulWidget {
@ -33,6 +35,7 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
AppData appData = AppData(); AppData appData = AppData();
late int currentSongIndex; late int currentSongIndex;
late AudioPlayer _audioPlayer; late AudioPlayer _audioPlayer;
StreamSubscription? _playerStateSubscription;
final downloadManager = Get.put(DownloadManager()); final downloadManager = Get.put(DownloadManager());
@ -62,31 +65,33 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
void initState() { void initState() {
super.initState(); super.initState();
currentSongIndex = widget.initialSongIndex; currentSongIndex = widget.initialSongIndex;
// _initializeAsync();
_fetchSonglistData();
_updateCurrentSong();
playerInit(); playerInit();
_initializeAsync();
_rotationController = AnimationController( _rotationController = AnimationController(
duration: const Duration(seconds: 20), duration: const Duration(seconds: 20),
vsync: this, vsync: this,
); );
// 2. _playerStateSubscription = _audioPlayer.playerStateStream.listen((state) {
_audioPlayer.playerStateStream.listen((state) { if (!_isDisposed) {
if (state.playing) { if (state.playing) {
//
_rotationController.repeat(); _rotationController.repeat();
} else { } else {
// _rotationController.stop();
_rotationController.stop(canceled: false); }
} }
}); });
} }
@override @override
void dispose() { void dispose() {
_isDisposed = true; _isDisposed = true;
_audioPlayer.dispose(); _playerStateSubscription?.cancel();
_rotationController.stop();
_rotationController.dispose(); _rotationController.dispose();
_audioPlayer.dispose();
super.dispose(); super.dispose();
} }
@ -94,17 +99,60 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
setState(() { setState(() {
for (int i = 0; i < widget.songList.length; i++) { for (int i = 0; i < widget.songList.length; i++) {
id.add(widget.songList[i].id); id.add(widget.songList[i].id);
song2.add(widget.songList[i].musicurl); // TODO musicurl ,
if (widget.songList[i].musicurl == null) {
song2.add("");
} else {
song2.add(widget.songList[i].musicurl!);
}
artist.add(widget.songList[i].artist); artist.add(widget.songList[i].artist);
music.add(widget.songList[i].title); music.add(widget.songList[i].title);
likes.add(widget.songList[i].likes);
collection.add(widget.songList[i].collection); //
likes.add(widget.songList[i].likes ?? false);
collection.add(widget.songList[i].collection ?? false);
}
});
} }
//
Future<void> _checkAndUpdateSongStatus(int index) async {
// likescollectionnull
if (widget.songList[index].likes == null || widget.songList[index].collection == null) {
try {
MusicListBean musicListBean = await GetMusic().getMusicById(
id: id[index],
Authorization: AppData().currentToken,
);
if (!_isDisposed && musicListBean.code == 200) {
setState(() {
likes[index] = musicListBean.likeOrNot!;
collection[index] = musicListBean.collectOrNot!;
//
if (index == currentSongIndex) {
likesnot = musicListBean.likeOrNot!;
collectionsnot = musicListBean.collectOrNot!;
}
widget.onSongStatusChanged?.call(
index,
musicListBean.collectOrNot!,
musicListBean.likeOrNot!,
);
}); });
} }
} catch (e) {
print('Error fetching song status: $e');
}
}
}
Future<void> _updateCurrentSong() async { Future<void> _updateCurrentSong() async {
// UI if (_isDisposed) return;
setState(() { setState(() {
_isLoading = true; _isLoading = true;
_position = Duration.zero; _position = Duration.zero;
@ -115,22 +163,23 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
collectionsnot = collection[currentSongIndex]; collectionsnot = collection[currentSongIndex];
}); });
await _checkAndUpdateSongStatus(currentSongIndex);
try { try {
//
await _audioPlayer.stop(); await _audioPlayer.stop();
_rotationController.reset(); _rotationController.reset();
// Check for local file first //
final localSong = downloadManager.getLocalSong(currentSongIndex); final localSong = downloadManager.getLocalSong(currentSongIndex);
final audioSource = localSong != null final audioSource = localSong != null
? AudioSource.file(localSong.musicurl) ? AudioSource.file(localSong.musicurl!)
: AudioSource.uri(Uri.parse(song2[currentSongIndex])); : AudioSource.uri(Uri.parse(song2[currentSongIndex]));
// Set the audio source and get duration //
final duration = await _audioPlayer.setAudioSource( await _audioPlayer.setAudioSource(audioSource, preload: true);
audioSource,
preload: true, //
); final duration = await _audioPlayer.duration;
if (!_isDisposed) { if (!_isDisposed) {
setState(() { setState(() {
@ -151,35 +200,86 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
} }
} }
void playerInit() { void playerInit() async {
_audioPlayer = AudioPlayer(); _audioPlayer = AudioPlayer();
await _checkAndUpdateSongStatus(widget.initialSongIndex);
// Initialize with first song //
artistName = widget.songList[widget.initialSongIndex].artist; artistName = widget.songList[widget.initialSongIndex].artist;
musicName = widget.songList[widget.initialSongIndex].title; musicName = widget.songList[widget.initialSongIndex].title;
likesnot = widget.songList[widget.initialSongIndex].likes; likesnot = widget.songList[widget.initialSongIndex].likes!;
collectionsnot = widget.songList[widget.initialSongIndex].collection; collectionsnot = widget.songList[widget.initialSongIndex].collection!;
// Listen to player events //
_audioPlayer.positionStream.listen((position) { _audioPlayer.positionStream.listen((position) {
if (!_isDisposed) { if (!_isDisposed) {
setState(() => _position = position); setState(() => _position = position);
} }
}); });
//
_audioPlayer.durationStream.listen((duration) { _audioPlayer.durationStream.listen((duration) {
if (!_isDisposed) { if (!_isDisposed) {
setState(() => _duration = duration ?? Duration.zero); setState(() => _duration = duration ?? Duration.zero);
} }
}); });
_audioPlayer.processingStateStream.listen((state) { //
if (state == ProcessingState.completed) { _audioPlayer.playerStateStream.listen((state) {
if (_isDisposed) return;
if (state.processingState == ProcessingState.completed) {
// Stream
_handleSongCompletion();
}
});
}
//
void _handleSongCompletion() {
if (_isDisposed) return;
setState(() {
_position = Duration.zero;
_duration = Duration.zero;
});
// 使 Future.microtask
Future.microtask(() {
if (!_isDisposed) {
playNextSong(); playNextSong();
} }
}); });
} }
// Slider
Widget _buildProgressSlider() {
// 0.1
final max = _duration.inSeconds.toDouble() == 0 ? 0.1 : _duration.inSeconds.toDouble();
//
final current = _position.inSeconds.toDouble().clamp(0, max);
return SliderTheme(
data: const SliderThemeData(
trackHeight: 3.0,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 7.0),
overlayShape: RoundSliderOverlayShape(overlayRadius: 12.0),
),
child: Slider(
min: 0,
max: max,
value: current.toDouble(),
onChanged: (value) async {
if (!_isDisposed && _duration.inSeconds > 0) {
await _audioPlayer.seek(Duration(seconds: value.toInt()));
setState(() {});
}
},
activeColor: const Color(0xff429482),
inactiveColor: const Color(0xffE3F0ED),
),
);
}
Widget _buildPlayButton() { Widget _buildPlayButton() {
return SizedBox( return SizedBox(
width: 52, width: 52,
@ -216,15 +316,23 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
} }
void playOrPause() async { void playOrPause() async {
if (_isDisposed) return; //
if (_audioPlayer.playing) { if (_audioPlayer.playing) {
await _audioPlayer.pause(); await _audioPlayer.pause();
_rotationController.stop(canceled: false); if (!_isDisposed) { //
_rotationController.stop();
}
} else { } else {
await _audioPlayer.play(); await _audioPlayer.play();
if (!_isDisposed) { //
_rotationController.repeat(); _rotationController.repeat();
} }
}
if (!_isDisposed) {
setState(() {}); setState(() {});
} }
}
void playNextSong() { void playNextSong() {
if (currentSongIndex < widget.songList.length - 1) { if (currentSongIndex < widget.songList.length - 1) {
@ -468,7 +576,12 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => CommentView(initialSongIndex: widget.initialSongIndex), builder: (context) => CommentView(
id: id[currentSongIndex],
song: musicName,
singer: artistName,
cover: widget.songList[currentSongIndex].artistPic,
),
), ),
); );
}, },
@ -489,39 +602,15 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text( Text(
"${formatDuration(_position)}", formatDuration(_position),
style: const TextStyle( style: const TextStyle(color: Colors.black),
color: Colors.black,
),
), ),
Expanded( Expanded(
child: SliderTheme( child: _buildProgressSlider(),
data: const SliderThemeData(
trackHeight: 3.0, //
thumbShape: RoundSliderThumbShape(
enabledThumbRadius: 7.0), //
overlayShape:
RoundSliderOverlayShape(overlayRadius: 12.0),
),
child: Slider(
min: 0,
max: _duration.inSeconds.toDouble(),
value: _position.inSeconds.toDouble(),
onChanged: (value) async {
await _audioPlayer
.seek(Duration(seconds: value.toInt()));
setState(() {});
},
activeColor: const Color(0xff429482),
inactiveColor: const Color(0xffE3F0ED),
),
),
), ),
Text( Text(
"${formatDuration(_duration)}", formatDuration(_duration),
style: const TextStyle( style: const TextStyle(color: Colors.black),
color: Colors.black,
),
), ),
], ],
), ),
@ -605,6 +694,9 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
), ),
), ),
), ),
const SizedBox(
height: 10,
),
Expanded( Expanded(
child: ListView.builder( child: ListView.builder(
itemCount: music.length, itemCount: music.length,
@ -641,21 +733,6 @@ class _MusicViewState extends State<MusicView> with SingleTickerProviderStateMix
}, },
), ),
), ),
ElevatedButton(
onPressed: () => Navigator.pop(context),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xff429482),
padding: const EdgeInsets.symmetric(vertical: 14),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.zero,
),
),
child: const Text(
"关闭",
style: TextStyle(color: Colors.black, fontSize: 20),
),
),
], ],
), ),
); );

@ -0,0 +1,507 @@
// music_view_test.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../common/audio_player_controller.dart';
import '../common/download_manager.dart';
import '../common_widget/Song_widegt.dart';
import '../common_widget/app_data.dart';
import 'comment_view.dart';
class MusicView extends StatefulWidget {
final List<Song> songList;
final int initialSongIndex;
final Function(int index, bool isCollected, bool isLiked)?
onSongStatusChanged;
const MusicView({
super.key,
required this.songList,
required this.initialSongIndex,
this.onSongStatusChanged,
});
@override
State<MusicView> createState() => _MusicViewState();
}
class _MusicViewState extends State<MusicView>
with SingleTickerProviderStateMixin {
// late AnimationController _rotationController;
final AudioPlayerController playerController =
Get.put(AudioPlayerController());
final downloadManager = Get.find<DownloadManager>();
final AppData appData = AppData();
@override
void initState() {
super.initState();
playerController.initWithSongs(widget.songList, widget.initialSongIndex);
}
@override
void dispose() {
super.dispose();
}
String formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "$twoDigitMinutes:$twoDigitSeconds";
}
Widget _buildProgressSlider() {
return Obx(() {
final max = playerController.duration.value.inSeconds.toDouble() == 0
? 0.1
: playerController.duration.value.inSeconds.toDouble();
final current =
playerController.position.value.inSeconds.toDouble().clamp(0, max);
return SliderTheme(
data: const SliderThemeData(
trackHeight: 3.0,
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 7.0),
overlayShape: RoundSliderOverlayShape(overlayRadius: 12.0),
),
child: Slider(
min: 0,
max: max,
value: current.toDouble(),
onChanged: (value) {
playerController.seekTo(Duration(seconds: value.toInt()));
},
activeColor: const Color(0xff429482),
inactiveColor: const Color(0xffE3F0ED),
),
);
});
}
Widget _buildPlayButton() {
return Obx(() {
return SizedBox(
width: 52,
height: 52,
child: Center(
child: playerController.isLoading.value
? const CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Color(0xff429482)),
strokeWidth: 3.0,
)
: IconButton(
padding: EdgeInsets.zero,
constraints: const BoxConstraints(
minWidth: 52,
minHeight: 52,
maxWidth: 52,
maxHeight: 52,
),
onPressed: playerController.playOrPause,
icon: !playerController.isPlaying.value
? Image.asset(
"assets/img/music_play.png",
width: 52,
height: 52,
)
: Image.asset(
"assets/img/music_pause.png",
width: 52,
height: 52,
),
),
),
);
});
}
// Widget _buildRotatingAlbumCover() {
// return Obx(() {
// final currentSong =
// widget.songList[playerController.currentSongIndex.value];
// return RotationTransition(
// turns: _rotationController,
// child: Stack(
// alignment: Alignment.center,
// children: [
// Positioned(
// child: ClipRRect(
// child: Image.network(
// currentSong.artistPic,
// width: 225,
// height: 225,
// fit: BoxFit.cover,
// ),
// ),
// ),
// ClipRRect(
// child: Image.asset(
// "assets/img/music_Ellipse.png",
// width: 350,
// height: 350,
// fit: BoxFit.cover,
// ),
// ),
// ],
// ),
// );
// });
// }
Widget _buildRotatingAlbumCover() {
return Obx(() {
final currentSong =
widget.songList[playerController.currentSongIndex.value];
// RotationTransition
return Stack(
alignment: Alignment.center,
children: [
Positioned(
child: ClipRRect(
child: Image.network(
currentSong.artistPic,
width: 225,
height: 225,
fit: BoxFit.cover,
),
),
),
ClipRRect(
child: Image.asset(
"assets/img/music_Ellipse.png",
width: 350,
height: 350,
fit: BoxFit.cover,
),
),
],
);
});
}
void _showPlaylist() {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
),
builder: (BuildContext context) {
return Container(
padding: const EdgeInsets.only(top: 15),
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.45,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Center(
child: Text(
"播放列表",
style: TextStyle(fontSize: 20),
),
),
const SizedBox(height: 10),
Expanded(
child: Obx(() => ListView.builder(
itemCount: playerController.musicNames.length,
itemBuilder: (BuildContext context, int index) {
final isCurrentlyPlaying =
playerController.currentSongIndex.value == index;
return ListTile(
tileColor: isCurrentlyPlaying
? const Color(0xffE3F0ED)
: null,
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(left: 20),
child: Text(
playerController.musicNames[index],
style: const TextStyle(fontSize: 18),
),
),
Padding(
padding: const EdgeInsets.only(right: 20),
child: Image.asset(
"assets/img/songs_run.png",
width: 25,
),
),
],
),
onTap: () {
playerController.changeSong(index);
Navigator.pop(context);
},
);
},
)),
),
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/img/app_bg.png"),
fit: BoxFit.cover,
),
),
child: Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.transparent,
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.only(top: 45, left: 10, right: 10),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
Get.back();
},
icon: Image.asset(
"assets/img/back.png",
width: 25,
height: 25,
fit: BoxFit.contain,
),
),
Row(
children: [
IconButton(
onPressed: () {},
icon: Image.asset(
"assets/img/music_add.png",
width: 30,
height: 30,
),
),
Obx(() => IconButton(
onPressed: downloadManager.isDownloading(
playerController.ids[playerController
.currentSongIndex.value]) ||
downloadManager.isCompleted(
playerController.ids[playerController
.currentSongIndex.value])
? null
: () async {
await downloadManager.startDownload(
song: widget.songList[playerController
.currentSongIndex.value],
context: context,
);
},
icon: Obx(() {
if (downloadManager.isDownloading(
playerController.ids[playerController
.currentSongIndex.value])) {
return Stack(
alignment: Alignment.center,
children: [
SizedBox(
width: 32,
height: 32,
child: CircularProgressIndicator(
value: downloadManager.getProgress(
playerController.ids[
playerController
.currentSongIndex.value]),
backgroundColor: Colors.grey[200],
valueColor:
const AlwaysStoppedAnimation<
Color>(Color(0xff429482)),
strokeWidth: 3.0,
),
),
Text(
'${(downloadManager.getProgress(playerController.ids[playerController.currentSongIndex.value]) * 100).toInt()}',
style: const TextStyle(fontSize: 12),
),
],
);
}
return Image.asset(
downloadManager.isCompleted(
playerController.ids[playerController
.currentSongIndex.value])
? "assets/img/music_download_completed.png"
: "assets/img/music_download.png",
width: 30,
height: 30,
);
}),
)),
],
),
],
),
const SizedBox(height: 80),
Center(child: _buildRotatingAlbumCover()),
const SizedBox(height: 60),
Obx(() => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
playerController.musicName.value,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Text(
playerController.artistName.value,
style: const TextStyle(fontSize: 20),
),
],
),
Row(
children: [
IconButton(
onPressed: () async {
playerController.toggleLike();
final currentIndex =
playerController.currentSongIndex.value;
widget.onSongStatusChanged?.call(
currentIndex,
playerController.collections[currentIndex],
playerController.likes[currentIndex],
);
},
icon: Image.asset(
playerController.likesStatus.value
? "assets/img/music_good.png"
: "assets/img/music_good_un.png",
width: 29,
height: 29,
),
),
IconButton(
onPressed: () async {
playerController.toggleCollection();
final currentIndex =
playerController.currentSongIndex.value;
widget.onSongStatusChanged?.call(
currentIndex,
playerController.collections[currentIndex],
playerController.likes[currentIndex],
);
},
icon: Image.asset(
playerController.collectionsStatus.value
? "assets/img/music_star.png"
: "assets/img/music_star_un.png",
width: 29,
height: 29,
),
),
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CommentView(
id: playerController.ids[playerController
.currentSongIndex.value],
song: playerController.musicName.value,
singer: playerController.artistName.value,
cover: widget
.songList[playerController
.currentSongIndex.value]
.artistPic,
),
),
);
},
icon: Image.asset(
"assets/img/music_commend_un.png",
width: 29,
height: 29,
),
),
],
),
],
)),
const SizedBox(height: 80),
Obx(() => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
formatDuration(playerController.position.value),
style: const TextStyle(color: Colors.black),
),
Expanded(child: _buildProgressSlider()),
Text(
formatDuration(playerController.duration.value),
style: const TextStyle(color: Colors.black),
),
],
)),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {},
icon: Image.asset(
"assets/img/music_random.png",
width: 35,
height: 35,
),
),
Row(
children: [
IconButton(
onPressed: playerController.playPrevious,
icon: Image.asset(
"assets/img/music_back.png",
width: 42,
height: 42,
),
),
const SizedBox(width: 10),
_buildPlayButton(),
const SizedBox(width: 10),
IconButton(
onPressed: playerController.playNext,
icon: Image.asset(
"assets/img/music_next.png",
width: 42,
height: 42,
),
),
],
),
IconButton(
onPressed: _showPlaylist,
icon: Image.asset(
"assets/img/music_more.png",
width: 35,
height: 35,
),
),
],
),
],
),
),
),
),
);
}
}

@ -15,7 +15,7 @@ class RankView extends StatefulWidget {
State<RankView> createState() => _RankViewState(); State<RankView> createState() => _RankViewState();
} }
class _RankViewState extends State<RankView> { class _RankViewState extends State<RankView> with AutomaticKeepAliveClientMixin {
final rankVM = Get.put(RankViewModel()); final rankVM = Get.put(RankViewModel());
List rankNames = []; List rankNames = [];
List rankSingerName = []; List rankSingerName = [];
@ -25,20 +25,41 @@ class _RankViewState extends State<RankView> {
final downloadManager = Get.put(DownloadManager()); final downloadManager = Get.put(DownloadManager());
@override
bool get wantKeepAlive => true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_fetchSonglistData(); _fetchTop50Data();
} }
Future<void> _fetchSonglistData() async { Future<void> _onRefresh() async {
await _fetchTop50Data();
}
Future<void> _fetchTop50Data() async {
try {
RankBean bean2 = await GetRank().getRank(Authorization: AppData().currentToken); RankBean bean2 = await GetRank().getRank(Authorization: AppData().currentToken);
if (bean2.code != 200) return;
rankNames.clear();
rankSingerName.clear();
rankCoverPath.clear();
rankMusicPath.clear();
setState(() { setState(() {
List<int> ids = bean2.data!.map((data) => data.id!).toList();
rankNames = bean2.data!.map((data) => data.name!).toList(); rankNames = bean2.data!.map((data) => data.name!).toList();
rankSingerName = bean2.data!.map((data) => data.singerName!).toList(); rankSingerName = bean2.data!.map((data) => data.singerName!).toList();
rankCoverPath = bean2.data!.map((data) => data.coverPath!).toList(); rankCoverPath = bean2.data!.map((data) => data.coverPath!).toList();
rankMusicPath = bean2.data!.map((data) => data.musicPath!).toList(); rankMusicPath = bean2.data!.map((data) => data.musicPath!).toList();
for (int i = 0; i < ids.length; i++) {
print(ids[i]);
}
songs.clear();
if (rankNames.isNotEmpty && if (rankNames.isNotEmpty &&
rankNames.length == rankSingerName.length && rankNames.length == rankSingerName.length &&
rankNames.length == rankCoverPath.length && rankNames.length == rankCoverPath.length &&
@ -50,17 +71,22 @@ class _RankViewState extends State<RankView> {
artist: rankSingerName[i], artist: rankSingerName[i],
musicurl: rankMusicPath[i], musicurl: rankMusicPath[i],
pic: rankCoverPath[i], pic: rankCoverPath[i],
id: i, id: ids[i],
likes: false, likes: null,
collection: false, collection: null,
)); ));
} }
} }
}); });
} catch (e) {
//
print('Error fetching data: $e');
}
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Container( return Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
image: DecorationImage( image: DecorationImage(
@ -74,20 +100,19 @@ class _RankViewState extends State<RankView> {
body: Column( body: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const SizedBox( const SizedBox(height: 40),
height: 40,
),
// //
const Center( const Center(
child: Column( child: Column(
children: [ children: [
SizedBox(
height: 10,
),
Text( Text(
'喵听排行榜', '喵听排行榜',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w400), style: TextStyle(fontSize: 22, fontWeight: FontWeight.w400),
), ),
SizedBox( SizedBox(height: 10),
height: 10,
),
Text( Text(
'Top50', 'Top50',
style: TextStyle( style: TextStyle(
@ -95,19 +120,15 @@ class _RankViewState extends State<RankView> {
fontSize: 40, fontSize: 40,
fontWeight: FontWeight.w500), fontWeight: FontWeight.w500),
), ),
SizedBox( // SizedBox(height: 10),
height: 10, // Text(
), // '2023/12/12更新 1期',
Text( // style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
'2023/12/12更新 1期', // ),
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
),
], ],
), ),
), ),
const SizedBox( const SizedBox(height: 10),
height: 10,
),
Container( Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
color: Colors.white, color: Colors.white,
@ -119,7 +140,25 @@ class _RankViewState extends State<RankView> {
child: Row( child: Row(
children: [ children: [
IconButton( IconButton(
onPressed: () {}, onPressed: () {
//
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MusicView(
songList: songs,
initialSongIndex: 0,
onSongStatusChanged: (index, isCollected, isLiked) {
setState(() {
songs[index].collection = isCollected;
songs[index].likes = isLiked;
downloadManager.updateSongInfo(songs[index].id, isCollected, isLiked);
});
},
),
),
);
},
icon: Image.asset( icon: Image.asset(
"assets/img/button_play.png", "assets/img/button_play.png",
width: 20, width: 20,
@ -130,9 +169,7 @@ class _RankViewState extends State<RankView> {
'播放全部', '播放全部',
style: TextStyle(fontSize: 16), style: TextStyle(fontSize: 16),
), ),
const SizedBox( const SizedBox(width: 5),
width: 5,
),
const Text( const Text(
'50', '50',
style: TextStyle(fontSize: 16), style: TextStyle(fontSize: 16),
@ -141,8 +178,11 @@ class _RankViewState extends State<RankView> {
), ),
), ),
Expanded( Expanded(
child: RefreshIndicator(
onRefresh: _onRefresh,
color: const Color(0xff429482),
child: SingleChildScrollView( child: SingleChildScrollView(
physics: const BouncingScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(), //
child: Container( child: Container(
color: Colors.white, color: Colors.white,
child: Column( child: Column(
@ -165,7 +205,6 @@ class _RankViewState extends State<RankView> {
initialSongIndex: index, initialSongIndex: index,
onSongStatusChanged: (index, isCollected, isLiked) { onSongStatusChanged: (index, isCollected, isLiked) {
setState(() { setState(() {
//
songs[index].collection = isCollected; songs[index].collection = isCollected;
songs[index].likes = isLiked; songs[index].likes = isLiked;
downloadManager.updateSongInfo(songs[index].id, isCollected, isLiked); downloadManager.updateSongInfo(songs[index].id, isCollected, isLiked);
@ -180,8 +219,7 @@ class _RankViewState extends State<RankView> {
Row( Row(
children: [ children: [
Row( Row(
mainAxisAlignment: mainAxisAlignment: MainAxisAlignment.center,
MainAxisAlignment.center,
children: [ children: [
SizedBox( SizedBox(
width: 25, width: 25,
@ -196,28 +234,21 @@ class _RankViewState extends State<RankView> {
), ),
), ),
), ),
const SizedBox( const SizedBox(width: 10),
width: 10,
),
ClipRRect( ClipRRect(
borderRadius: borderRadius: BorderRadius.circular(10),
BorderRadius.circular(10),
child: Image.network( child: Image.network(
rankCoverPath[index], rankCoverPath[index],
width: 60, width: 60,
height: 60, height: 60,
fit: BoxFit.cover, fit: BoxFit.cover,
), ),
), ),
const SizedBox( const SizedBox(width: 20),
width: 20,
),
SizedBox( SizedBox(
width: 170, width: 170,
child: Column( child: Column(
crossAxisAlignment: crossAxisAlignment: CrossAxisAlignment.start,
CrossAxisAlignment.start,
children: [ children: [
Text( Text(
rankNames[index], rankNames[index],
@ -225,50 +256,48 @@ class _RankViewState extends State<RankView> {
style: const TextStyle( style: const TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 16, fontSize: 16,
fontWeight: fontWeight: FontWeight.w400
FontWeight.w400), ),
), ),
Text( Text(
rankSingerName[index], rankSingerName[index],
maxLines: 1, maxLines: 1,
style: const TextStyle( style: const TextStyle(
color: Colors.black, color: Colors.black,
fontSize: 14), fontSize: 14
),
) )
], ],
), ),
), ),
const SizedBox( const SizedBox(width: 18),
width: 18, ],
), ),
// IconButton(
// onPressed: () {
// _bottomSheet(context, index);
// },
// icon: Image.asset(
// 'assets/img/More.png',
// width: 25,
// height: 25,
// errorBuilder: (context, error, stackTrace) {
// print('Error loading image: $error');
// return const Icon(Icons.error, size: 25);
// },
// ),
// ),
], ],
), ),
IconButton( const SizedBox(height: 10)
onPressed: () { ],
_bottomSheet(context, index); // index
},
icon: Image.asset(
'assets/img/More.png',
width: 25,
height: 25,
errorBuilder: (context, error, stackTrace) {
print('Error loading image: $error');
return const Icon(Icons.error, size: 25); // 使 const
},
), ),
);
},
), ),
const SizedBox(
height: 20,
)
], ],
), ),
const SizedBox(
height: 10,
)
],
));
}),
],
), ),
), ),
), ),
@ -278,12 +307,15 @@ class _RankViewState extends State<RankView> {
), ),
); );
} }
Future _bottomSheet(BuildContext context, int index){
Future _bottomSheet(BuildContext context, int index) {
return showModalBottomSheet( return showModalBottomSheet(
context: context, context: context,
backgroundColor: Colors.white, backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(30))), shape: const RoundedRectangleBorder(
builder: (context) =>Container( borderRadius: BorderRadius.vertical(top: Radius.circular(30))
),
builder: (context) => Container(
height: 150, height: 150,
padding: const EdgeInsets.only(top: 20), padding: const EdgeInsets.only(top: 20),
child: Column( child: Column(
@ -349,7 +381,6 @@ class _RankViewState extends State<RankView> {
], ],
), ),
) )
); );
} }
} }

@ -24,7 +24,7 @@ class SongInfo {
SongInfo({required this.songName, required this.artistName}); SongInfo({required this.songName, required this.artistName});
} }
class _ReleaseViewState extends State<ReleaseView> { class _ReleaseViewState extends State<ReleaseView> with AutomaticKeepAliveClientMixin {
List<File> coverImages = []; List<File> coverImages = [];
List<SongInfo> songInfoList = []; List<SongInfo> songInfoList = [];
@ -35,8 +35,12 @@ class _ReleaseViewState extends State<ReleaseView> {
bool isUploading = false; bool isUploading = false;
double uploadProgress = 0.0; double uploadProgress = 0.0;
@override
bool get wantKeepAlive => true;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Scaffold( return Scaffold(
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
backgroundColor: Colors.transparent, backgroundColor: Colors.transparent,

@ -24,7 +24,7 @@ class UserView extends StatefulWidget {
State<UserView> createState() => _UserViewState(); State<UserView> createState() => _UserViewState();
} }
class _UserViewState extends State<UserView> { class _UserViewState extends State<UserView> with AutomaticKeepAliveClientMixin {
final homeVM = Get.put(HomeViewModel()); final homeVM = Get.put(HomeViewModel());
final TextEditingController _controller = TextEditingController(); final TextEditingController _controller = TextEditingController();
int playlistCount = 0; int playlistCount = 0;
@ -36,6 +36,9 @@ class _UserViewState extends State<UserView> {
final downloadManager = Get.put(DownloadManager()); final downloadManager = Get.put(DownloadManager());
@override
bool get wantKeepAlive => true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -61,6 +64,7 @@ class _UserViewState extends State<UserView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context);
return Container( return Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
image: DecorationImage( image: DecorationImage(
@ -86,10 +90,14 @@ class _UserViewState extends State<UserView> {
children: [ children: [
Row( Row(
children: [ children: [
Image.network( ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
avatar, avatar,
width: 64, width: 60,
height: 64, height: 60,
fit: BoxFit.cover,
),
), ),
const SizedBox( const SizedBox(
width: 25, width: 25,
@ -123,7 +131,12 @@ class _UserViewState extends State<UserView> {
children: [ children: [
InkWell( InkWell(
onTap: () { onTap: () {
Get.to(const MyMusicView()); Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MyMusicView(),
),
);
}, },
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
@ -159,7 +172,12 @@ class _UserViewState extends State<UserView> {
// //
InkWell( InkWell(
onTap: () async { onTap: () async {
final result = await Get.to(const MyDownloadView()); final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyDownloadView(),
),
);
if (result == true) { if (result == true) {
setState(() { setState(() {
@ -252,7 +270,14 @@ class _UserViewState extends State<UserView> {
InkWell( InkWell(
onTap: () { onTap: () {
print('点击成功'); print('点击成功');
Get.to(MyMusicView(songlistIdd: playlistid[index])); Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyMusicView(
songlistIdd: playlistid[index]
),
),
);
}, },
child: Row( child: Row(
children: [ children: [
@ -304,7 +329,12 @@ class _UserViewState extends State<UserView> {
children: [ children: [
InkWell( InkWell(
onTap: () { onTap: () {
Get.to(const MyWorkView()); Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MyWorkView(),
),
);
}, },
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
@ -365,7 +395,12 @@ class _UserViewState extends State<UserView> {
IconButton( IconButton(
onPressed: () async { onPressed: () async {
Navigator.pop(context); Navigator.pop(context);
bool result = await Get.to(const UserInfo()); bool result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UserInfo(),
),
);
if (result) { if (result) {
setState(() { setState(() {
avatar = AppData().currentAvatar; avatar = AppData().currentAvatar;
@ -388,6 +423,9 @@ class _UserViewState extends State<UserView> {
UniversalBean bean = await LogoutApiClient().logout( UniversalBean bean = await LogoutApiClient().logout(
Authorization: AppData().currentToken, Authorization: AppData().currentToken,
); );
AppData().currentToken = '';
AppData().currentUsername = '';
AppData().currentAvatar = '';
}, },
icon: Image.asset("assets/img/user_out.png"), icon: Image.asset("assets/img/user_out.png"),
iconSize: 60, iconSize: 60,

@ -8,6 +8,7 @@ class TextFieldColor extends StatelessWidget {
final String? Function(String?)? validator; final String? Function(String?)? validator;
final FocusNode? focusNode; final FocusNode? focusNode;
final String? Function(String?)? onChanged; final String? Function(String?)? onChanged;
final bool enabled; // enabled
const TextFieldColor({ const TextFieldColor({
super.key, super.key,
@ -18,11 +19,13 @@ class TextFieldColor extends StatelessWidget {
this.validator, this.validator,
this.focusNode, this.focusNode,
this.onChanged, this.onChanged,
this.enabled = true, //
}); });
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return TextFormField( return TextFormField(
enabled: enabled,
validator: validator, validator: validator,
controller: controller, controller: controller,
focusNode: focusNode, focusNode: focusNode,
@ -35,22 +38,25 @@ class TextFieldColor extends StatelessWidget {
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0), contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none borderSide: BorderSide.none,
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none, borderSide: BorderSide.none,
), ),
fillColor: Color(0xffE3F0ED), disabledBorder: OutlineInputBorder( //
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
),
fillColor: enabled ? const Color(0xffE3F0ED) : const Color(0xffE3F0ED).withOpacity(0.7), //
filled: true, filled: true,
hintText: hintText, hintText: hintText,
alignLabelWithHint: true, alignLabelWithHint: true,
hintStyle: TextStyle( hintStyle: TextStyle(
color: Color(0xff6E6E6E), color: enabled ? const Color(0xff6E6E6E) : const Color(0xff6E6E6E).withOpacity(0.5),
fontSize: 16 fontSize: 16,
), ),
), ),
); );
} }
} }
Loading…
Cancel
Save