creating playlist feature for astrology course app

i am currently amidst of migrating from flutterflow to flutter and i am encountering state management issues where the page that contains videos for creating playlist by normal user has a checkbox and on selecting the checkbox it should retrieve the video post item with relevant information and currently that doesn’t work here’s the relevant checkbox code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class PostItem extends StatefulWidget {
final QueryDocumentSnapshot post;
const PostItem({super.key, required this.post});
u/override
_PostItemState createState() => _PostItemState();
}
class _PostItemState extends State<PostItem> {
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'],
);
}
},
)
</code>
<code>class PostItem extends StatefulWidget { final QueryDocumentSnapshot post; const PostItem({super.key, required this.post}); u/override _PostItemState createState() => _PostItemState(); } class _PostItemState extends State<PostItem> { 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'], ); } }, ) </code>
class PostItem extends StatefulWidget {
  final QueryDocumentSnapshot post;

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

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

class _PostItemState extends State<PostItem> {
  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'],
                      );
                    }
                  },
                )

model of the page

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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<Contentfeed2Widget> {
/// 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<UserPosts2Record, bool> checkboxValueMap = {};
List<UserPosts2Record> 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();
}
}
</code>
<code>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<Contentfeed2Widget> { /// 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<UserPosts2Record, bool> checkboxValueMap = {}; List<UserPosts2Record> 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(); } } </code>
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<Contentfeed2Widget> {
  ///  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<UserPosts2Record, bool> checkboxValueMap = {};
  List<UserPosts2Record> 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();
  }
}

playlist creation button on the videos page

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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: <String, dynamic>{
'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')),
);
}
},
)
</code>
<code> 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: <String, dynamic>{ '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')), ); } }, ) </code>
            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: <String, dynamic>{
                      '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')),
                  );
                }
              },
            )

and the create playlist page accepts this parameter

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class CreateplaylistWidget extends StatefulWidget {
const CreateplaylistWidget({
super.key,
required this.createplaylist,
});
</code>
<code>class CreateplaylistWidget extends StatefulWidget { const CreateplaylistWidget({ super.key, required this.createplaylist, }); </code>
class CreateplaylistWidget extends StatefulWidget {
  const CreateplaylistWidget({
    super.key,
    required this.createplaylist,
  });

i have tried learning about state management solution like bloc changing type casting for firebase and changing query params

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật