Flutter BLoC and Card widget in ListView - flutter

I am a beginner in programming. I am currently trying to make an application that displays news from the firestore database.
I have created a Bloc, Repository and Service for Firestore and it works fine for now. Inside BlocBuilder I use a ListView Builder that displays the articles inside a Card widget.
Now I need inside each Card Widget to use Bloc for options like "Bookmarks", "Comments", "Reactions".
My question is the following. Is it correct to use the following solution:
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return BlocProvider(
create: (BuildContext context) => CardBloc(),
child: CardWidget(...),
);
},
)

Related

Flutter, How to print the position of the widget in a list after onTap?

I am dynamically adding card widget to a list and displaying the list in a screen using listView Builder, How do I get the index of the widget after onTap. For example if I tap on 4th card widget on the screen I should get the index of that widget.
It's hard to say without seeing your actual code, but in general you shouldn't be adding the widgets themselves in the list, but only the information needed to build the widgets. That way you create the widget in the builder, where you have access to the index.
Alternatively, you wrap the widget with a GestureDetector or similar in the builder. Something like
ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: ()=> print(index), //here you have access to it
child: items[index]
);
})

Flutter returning to same position in richtext in listview inside a pageview

I am trying to finish my first flutter app
it is a Quran app, and i was able so far to fetch and show the data in page view, each page has list view which contains the data depending on user selection, so one listview can be very long
in the list view there is a list of rich texts, each containing textspans,
here is the code
PageView.builder(
controller: _pageController,
itemCount: ConstantsHelper.selectionCount[widget.args.type],
scrollDirection: Axis.horizontal,
reverse: true,
itemBuilder: (context, index) => StreamBuilder<Object>(
stream: null,
builder: (context, snapshot) {
return FutureBuilder(
future: Provider.of<QuranProvider>(context)
.getSelection(widget.args.type, index + 1),
builder: (context, snapshot) =>
snapshot.connectionState == ConnectionState.waiting
? CircularProgressIndicator()
: ListView.builder(
itemCount: 1,
scrollDirection: Axis.vertical,
itemBuilder: (ctx, index) => Column(
children: WidgetHelper().getContent(
Provider.of<QuranProvider>(context)
.ayas,
context),
),
),
);
},
),
),
basically this is how the app looks like
one rich text can be so long that it requires lots of scrolling and can take the entire page
now, what I need to do, is getting the scrolling position, so when the user opens the app, the app will automatically scroll to the correct page and line
the page part is already done, however, when I try to implement the scrollController I get error ScrollController attached to multiple scroll views
I tried to set a listener in initstate to the scroll listener, the problem is that i am not sure where to add the controller and the listener
the controller.position doesnt change when i scroll, which is not useful.
so, how can I listen to the scrolling position change with a pageview parent?

Jump pages in Pageview.builder with Consumer

I'm trying to make a feed where once the users uploads a post, the post gets added to the top of the feed and the user can see the post they just made. Right now I have a ChangeNotifierProvider and Consumer that is getting newly updated data from my view model. Inside the ChangeNotifierProvider, I have a pageview.builder. How would I get the pageview.builder to refresh pages so that the users post is now shown? I have tried using the onPageJumped but I can't use that inside the ChangeNotifier.
Widget _buildScreen(VideoPlayerViewModel viewModel) {
return ChangeNotifierProvider<VideoPlayerViewModel>(
create: (context) => viewModel,
child: Consumer<VideoPlayerViewModel>(
builder: (context, model, child) => PageView.builder(
controller: pageController,
scrollDirection: Axis.vertical,
itemCount: videoPlayerViewModel.intialVideoDataLength,
itemBuilder: (BuildContext context, int index) {
var data = videoPlayerViewModel.intialVideoData;
return VideoScaffoldWidget(videoData: data[index]);
})));
}
Try adding unique key to the PageView, it should do the trick
PageView.builder(
key: UniqueKey(),

How to display data from MySQL database in table format in flutter application?

This is my code. Here, I have used Listview.builder due to which whole data is displayed in 1 tablecell. What should I use at place of listview to display the data properly in different cells.
Or Any other way to display data dynamically from backend?
TableRow(children: [
TableCell(
child: FutureBuilder(
future: fetchProducts(),
builder: (context, snapshot){
if(snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
shrinkWrap: true,
itemBuilder: (BuildContext context, index){
Products product = snapshot.data[index];
return Text(//"Name :- "
'${product.pname}', style: TextStyle(fontSize: 15));
});
}},
)),]),
In place of tablerow use DataTable, it will automatically size itself, it has column and row children so its probably the best way to display your data, check this youtube vide out
https://www.youtube.com/watch?v=ktTajqbhIcY&vl=en

Dart: Minimising access to Firebase in Flutter app

I have the following widget which builds a to-do list from a subcollection of a task given its document ID. The code is working fine.
Widget buildFoodList() {
return SizedBox(
child: Container(
padding: const EdgeInsets.all(10.0),
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('tasks').document(documentID).collection('todo')
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Text('Loading...');
default:
return new ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.documents[index];
return new Row(
children: <Widget>[
Expanded (child:Text(ds['deadline'].toString()) ),
Expanded (child:Text(ds['description']) ),
Expanded (child:Text("\$"+ds['quantity'].toString()) ),
],
);
},
);
}
},
)
),
);
}
As you can see, I am using a StreamBuilder. However, I know that the subcollection is not going to change. So the question is whether using StreamBuilder is an overkill, because using stream to listen can be a waste of resources and access to Firebase. More importantly, the cost of using Firebase is calculated on an access basis.
To summarise, the question is whether using StreamBuilder is necessary. If not, what is the alternative approach which can help to avoid unnecessary access to Firebase.
Thanks.
StreamBuilder is necessary in apps where you need to fetch any update , insert or delete in a firebase collection ( in this case ). An alternative can be the FutureBuilder that fetch the data once and then you can wrap in a Swipe to refresh ( and the user decides when needs to see new data).