Создание функции плейлиста для приложения курса астрологииAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Создание функции плейлиста для приложения курса астрологии

Сообщение Anonymous »

В настоящее время я перехожу с flutterflow на flutter, и сталкиваюсь с проблемами управления состоянием, когда на странице, содержащей видео для создания списка воспроизведения обычным пользователем, есть флажок, и при выборе флажка он должен получить элемент публикации видео с соответствующей информацией и в настоящее время это не работает, вот соответствующий код флажка

Код: Выделить всё

class PostItem extends StatefulWidget {
final QueryDocumentSnapshot post;

const PostItem({super.key, required this.post});

u/override
_PostItemState createState() => _PostItemState();
}

class _PostItemState extends State
 {
late Contentfeed2Model _model;
late DocumentReference _documentReference;

bool? isChecked;

@override
void initState() {
super.initState();
_model = createModel(context, () => Contentfeed2Model());
isChecked = false; // Initial checkbox state
_documentReference = widget.post.reference;
}

@override
Widget build(BuildContext context) {
var post = widget.post;
return Card(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
context.pushNamed(
'profilevisiting',
queryParameters: {
'postuser': serializeParam(
post['post_user'],
ParamType.String,
),
'profilepic': serializeParam(
post['postuser_photo'],
ParamType.String,
),
'userpostref': serializeParam(
post.reference,
ParamType.DocumentReference,
),
'postuserref': serializeParam(
post['post_useref'],
ParamType.DocumentReference,
),
}.withoutNulls,
);
},
child: Row(
children: [
CircleAvatar(
backgroundImage:
NetworkImage(post['postuser_photo'] ?? ''),
),
const SizedBox(width: 10),
Text(post['post_user'] ?? 'Unknown'),
],
),
),
const Spacer(),
Checkbox(
value: _model.ischecked,
onChanged: (bool? newValue) {
setState(() {
_model.ischecked = newValue ?? false;
});

// Handle checkbox state change here
if (newValue == true) {
String videoId = post['postID'];
String thumbnail = post['thumbnail'];
String videoUrl = post['video_url'];
String postUser = post['post_user'];

// Add the selected item to the list
_model.checkboxCheckedItems.add({
'postID': videoId,
'thumbnail': thumbnail,
'videoUrl': videoUrl,
'postUser': postUser,
} as UserPosts2Record);
} else {
// Remove the item from the list if unchecked
_model.checkboxCheckedItems.removeWhere(
(element) => element.postID == post['postID'],
);
}
},
)
модель страницы

Код: Выделить всё

import '/backend/backend.dart';
import '/flutter_flow/flutter_flow_util.dart';
import 'contentfeed2_widget.dart' show Contentfeed2Widget;
import 'package:flutter/material.dart';

class Contentfeed2Model extends FlutterFlowModel  {
///  Local state fields for this page.

bool ischecked = false;

bool ischeckedfree = false;

bool isliked = false;

bool paid = false;

///  State fields for stateful widgets in this page.

final unfocusNode = FocusNode();
// Stores action output result for [Firestore Query - Query a collection] action in Button widget.
PurchaseHistoryRecord? boughtornot;
// State field(s) for Checkbox widget.
Map checkboxValueMap = {};
List get checkboxCheckedItems =>
checkboxValueMap.entries.where((e) => e.value).map((e) => e.key).toList();

// Stores action output result for [Firestore Query - Query a collection] action in Checkbox widget.
UserPosts2Record? checkboxpostid;
// Stores action output result for [Backend Call - Create Document] action in IconButton widget.
PlaylistRecord? makeplaylistpurchasedpost;
// Stores action output result for [Backend Call - Create Document] action in IconButton widget.
PlaylistactualRecord? makeplaylist;

@override
void initState(BuildContext context) {}

@override
void dispose() {
unfocusNode.dispose();
}
}
Кнопка создания плейлиста на странице видео

Код: Выделить всё

            IconButton(
icon: const Icon(Icons.playlist_play, color: Color(0xFF420181)),
onPressed: () async {
if (_model.ischecked || _model.ischeckedfree) {
var playlistactualRecordReference =
PlaylistactualRecord.collection.doc(
'$currentUserDisplayName${getCurrentTimestamp.toString()}');
await playlistactualRecordReference.set({
...createPlaylistactualRecordData(
playlistId:
'$currentUserDisplayName${getCurrentTimestamp.toString()}',
createdBy: currentUserReference,
playlistName:
'$currentUserDisplayName${getCurrentTimestamp.toString()}',
coverimage: '',
),
...mapToFirestore(
{
'postid': _model.checkboxCheckedItems
.map((e) => e.postID)
.toList(),
'videopostpost': _model.checkboxCheckedItems
.map((e) => e.videoUrl)
.toList(),
'astrologer': _model.checkboxCheckedItems
.map((e) => e.postUser)
.toList(),
},
),
});
_model.makeplaylist =
PlaylistactualRecord.getDocumentFromData({
...createPlaylistactualRecordData(
playlistId:
'$currentUserDisplayName${getCurrentTimestamp.toString()}',
createdBy: currentUserReference,
playlistName:
'$currentUserDisplayName${getCurrentTimestamp.toString()}',
coverimage: '',
),
...mapToFirestore(
{
'postid': _model.checkboxCheckedItems
.map((e) => e.postID)
.toList(),
'videopostpost': _model.checkboxCheckedItems
.map((e) => e.videoUrl)
.toList(),
'astrologer': _model.checkboxCheckedItems
.map((e) =>  e.postUser)
.toList(),
},
),
}, playlistactualRecordReference);

context.pushNamed(
'createplaylist',
queryParameters: {
'createplaylist': serializeParam(
_model.makeplaylist,
ParamType.Document,
),
}.withoutNulls,
extra: {
'createplaylist': _model.makeplaylist,
},
);
} else {
// Show a message or handle the case when nothing is selected
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Please select at least one item')),
);
}
},
)
и страница создания плейлиста принимает этот параметр

Код: Выделить всё

class CreateplaylistWidget extends StatefulWidget {
const CreateplaylistWidget({
super.key,
required this.createplaylist,
});
Я пытался узнать о решении для управления состоянием, например, о приведении типов блоков для Firebase и изменении параметров запроса.

Подробнее здесь: https://stackoverflow.com/questions/788 ... course-app
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»