How to update a single item of a SliverList in Flutter? - flutter

Do you guys know how can I update a single item of a sliver list without having to invoke a setState() ?
In my case I have a SliverList and i want to click into an item and change it's color, the problem using setState() is that it rebuilds the whole UI in a not smooth way and also mess up with Custom Scroll position.
The funny thing is that this SliverList behaviour does not occur when using normal ListView, when use setState() on a ListView the load is smooth and it doesn't break the scroll state. Looks like the ListView can implicitely handle state better than SliverList.
But since I have a Custom Scroll I can't use ListVew it has to be SliverList
Any options ? Providers ?Notifiers ? Stream ? Bloc ?

Ok, after all, I could solve my need using a simple ChangeNotifier combined with an AnimatedBuilder inside each item of the SliverList, I'll post some high-level code of the solution - it works just fine for my need!
class ChangeColorSliverListItemNotifier extends ChangeNotifier {
int index;
Color current_label_color;
ChangeColorSliverListItemNotifier()
{
this.current_label_color = Colors.white;
}
void onTap(int selected_index)
{
index = selected_index;
this.current_label_color = Colors.yellow;
notifyListeners();
}
}
// code block inside SliverList items binding- changing only the color of the selected Widget
SliverList(
delegate: SliverChildBuilderDelegate((context, index)
{
return GestureDetector(
onTap:() {
changeColorSliverListItemNotifier.onTap(index);
},
child:AnimatedBuilder(
animation: changeColorSliverListItemNotifier,
builder: (_, __) =>
Row(children:[
Container(
margin: EdgeInsets.only(right:8),
child: Icon(Icons.edit,color:changeColorSliverListItemNotifier.index==index?changeColorSliverListItemNotifier.current_label_color:default_color,size: 20,)
),
])
)
)
....

Just in case you want to use the Riverpod state management library, I made the following.
class SliverScreen extends StatelessWidget {
const SliverScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: [
_appBar(),
_list(),
],
),
);
}
SliverFixedExtentList _list() {
return SliverFixedExtentList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListItem(index: index),
),
itemExtent: 100,
);
}
SliverAppBar _appBar() {
return SliverAppBar(
title: Text("Slivering..."),
backgroundColor: Colors.teal[900],
expandedHeight: 200,
pinned: true,
stretch: true,
flexibleSpace: FlexibleSpaceBar(
background: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.teal[100]!,
Colors.teal[600]!,
],
),
),
),
),
);
}
}
final colorStateProvider = StateProvider.family<Color, int>((ref, key) {
return Colors.blue[100]!;
});
class ListItem extends HookConsumerWidget {
final int index;
const ListItem({Key? key, required this.index}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final colorState = ref.watch(colorStateProvider(index));
return InkWell(
onTap: () => colorState.state = Colors.blue,
child: Container(
color: colorState.state,
child: Center(
child: Text("Item $index"),
),
),
);
}
}
If you click an item, it updates the color without rebuilding the whole list, only the item itself.

Related

Flutter - How to flip the previous card back using FlipCard

After days of search I'm getting help.
I work on a flutter application.
Context:
A grid view feeded with Json
-childs : GridTile with Flipcard in (https://pub.dev/packages/flip_card)
-On tap on GridTile there is a callback to get the selected Item and an animation because of the flipcard onTap
What I would:
When an item is aleready selected (flipcard flipped so we show the back of the card),
And I selected another item of the grid te(so flipcard of this itme also flipped)
I would like to flip back the old selected item Flipcard without rebuild the tree because I would lost the state of the new selected item.
I tried many thing. For example I tried to use GlobalKey on GridTiles to interract with after build but currentState is always null when I want to interact with.
I wonder what is the good practice in this case ?
I hope I was clear :) (I'm french)
Thank you the community!
.
Something to know...
It is possible to interract with the flipcard (child of gridtile) like this
(GlobalKey)
GlobalKey<FlipCardState> cardKey = GlobalKey<FlipCardState>();
#override
Widget build(BuildContext context) {
return FlipCard(
key: cardKey,
flipOnTouch: false,
front: Container(
child: RaisedButton(
onPressed: () => cardKey.currentState.toggleCard(),
child: Text('Toggle'),
),
),
back: Container(
child: Text('Back'),
),
);
}
I'm not sure if I understood your question, but here is an example of how you could use a GridView with FlipCards:
var cardKeys = Map<int, GlobalKey<FlipCardState>>();
GlobalKey<FlipCardState> lastFlipped;
Widget _buildFlipCard(String text, Color color, int index) {
return SizedBox(
height: 120.0,
child: Card(
color: color,
child: Center(
child:
Text(text, style: TextStyle(color: Colors.white, fontSize: 20.0)),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FlipCards")),
body: GridView.builder(
itemCount: 20,
itemBuilder: (context, index) {
cardKeys.putIfAbsent(index, () => GlobalKey<FlipCardState>());
GlobalKey<FlipCardState> thisCard = cardKeys[index];
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlipCardWithKeepAlive(
child: FlipCard(
flipOnTouch: false,
key: thisCard,
front: _buildFlipCard("$index", Colors.blue, index),
back: _buildFlipCard("$index", Colors.green, index),
onFlip: () {
if (lastFlipped != thisCard) {
lastFlipped?.currentState?.toggleCard();
lastFlipped = thisCard;
}
},
),
),
RaisedButton(
child: Text("Flip Card"),
onPressed: () => cardKeys[index].currentState.toggleCard(),
)
],
);
},
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
),
);
}
class FlipCardWithKeepAlive extends StatefulWidget {
final FlipCard child;
FlipCardWithKeepAlive({Key key, this.child}) : super(key: key);
#override
State<StatefulWidget> createState() => FlipCardWithKeepAliveState();
}
class FlipCardWithKeepAliveState extends State<FlipCardWithKeepAlive>
with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
#override
bool get wantKeepAlive => true;
}
You need to use a different key for each element of the list, I used a Map in this case.
I also wrapped the FlipCard with a custom FlipCardWithKeepAlive stateful widget that uses AutomaticKeepAliveClientMixin to keep alive the FlipCard while scrolling.
Edit: I updated the code so when you flip one card, the previous card flipped gets flipped back. Basically you need to save the last flipped card and when a new one is flipped, flip the last one and put the new one as last flipped.
The code will make both cards flip at the same time, if you want one card to wait the other use onFlipDone() instead of onFlip(), like this:
onFlipDone: (isFront) {
bool isFlipped = !isFront;
if (isFlipped && lastFlipped != thisCard) {
lastFlipped?.currentState?.toggleCard();
lastFlipped = thisCard;
}
}

Refresh widget or page in Flutter without ListView et al

I want refresh my page without having a scrollable content, i.e. without having a ListView et al.
When I want use RefreshIndicator, the documentation says it needs a scrollable widget like ListView.
But if I want to refresh and want to use the refresh animation of RefreshIndicator without using a ListView, GridView or any other scorllable widget, how can i do that?
You can simply wrap your content in a SingleChildScrollView, which will allow you to use a RefreshIndicator. In order to make the pull down to refresh interaction work, you will have to use AlwaysScrollableScrollPhysics as your content will most likely not cover more space than available without a scroll view:
RefreshIndicator(
onRefresh: () async {
// Handle refresh.
},
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: /* your content */,
),
);
You can just use GestureDetector, I have created a sample for you, but it's not perfect, you can customize it to your own needs, it just detects when you swipe from the top.
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
var refresh=false;
void refreshData(){
if(!refresh){
refresh=true;
print("Refreshing");
Future.delayed(Duration(seconds: 4),(){
refresh =false;
print("Refreshed");
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Test"),
centerTitle: true,
),
body: GestureDetector(
child: Container(
color: Colors.yellow,
height: double.infinity,
width: double.infinity,
child: Center(child: Text('TURN LIGHTS ON')),
),
onVerticalDragUpdate: (DragUpdateDetails details){
print("direction ${details.globalPosition.direction}");
print("distance ${details.globalPosition.distance}");
print("dy ${details.globalPosition.dy}");
if(details.globalPosition.direction < 1 && (details.globalPosition.dy >200 && details.globalPosition.dy < 250)){
refreshData();
}
},
));
}
}

How to specify ListTile height in Flutter

In this code, I am trying to make a list of buttons or tiles "as buttons do not work well for me " at the very top of the page. Thus, when one is clicked it returns a value in the rest of the page.
The issue is The tile here toke around more than half of the page which makes it looks inconsistent. I want to limit the height of the tile, I have tried putting them in a row and a container and it doesn't work. Any HELP will be appreciated.
the result after running the code is:
this is the error after runing the code :
class HomePage extends StatefulWidget {
// const HomePage({Key key}) : super(key: key);
#override
HomePageState createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
List<String> temp=new List();
List<String> temp1=['Nile University', 'Smart Village', 'Zewail'];
Map<String,String> map1={};
#override
void initState() {
super.initState();
getplaces(temp);
getuser(map1,'1jKpg81YCO5PoFOa2wWR');
}
Future<List> getuser(temp,String place) async{
List<String> userids=[];
QuerySnapshot usersubs= await Firestore.instance.collection('tempSubs').getDocuments();
QuerySnapshot userid= await Firestore.instance.collection('users').where('place',isEqualTo: place).getDocuments();
userid.documents.forEach((DocumentSnapshot doc,){
usersubs.documents.forEach((DocumentSnapshot doc1){
if(doc.documentID==doc1.documentID){
doc1.data['products'].forEach((k,v){
if( DateTime.fromMillisecondsSinceEpoch(v).day==DateTime.now().day){
int x= DateTime.fromMillisecondsSinceEpoch(v).day;
print('keey equal $k and v is $x');
print('dy is $x');
userids.add(
doc.documentID);
}
});
}
} ); }
);
print('doc.documentID');
print (userids);
setState(() {});
return userids;
}
Future<List> getplaces(temp) async{
QuerySnapshot place= await Firestore.instance.collection('places').getDocuments();
place.documents.forEach((DocumentSnapshot doc){
temp.add(
doc.data['name']
);
// print(doc.data['name']);
});
// print(temp);
setState(() {});
return temp;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Page"),
),
body: !temp.isNotEmpty?
CircularProgressIndicator():
Row(mainAxisSize:MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children:<Widget>[
Container(
height: 100.0,
child:
ListView.builder(
scrollDirection: Axis.horizontal,
itemExtent: 100.0,
itemCount:temp.length,
itemBuilder:(BuildContext context, int index) {
return ListTile(title: Text(temp[index]),onTap:
(){
print(temp[index]);
}
);}
),),
Container(child:Text('data'),)
],),
);
}
}
Applying VisualDensity allows you to expand or contract the height of list tile. VisualDensity is compactness of UI elements. Here is an example:
// negative value to contract
ListTile(
title: Text('Tile title'),
dense: true,
visualDensity: VisualDensity(vertical: -3), // to compact
onTap: () {
// tap actions
},
)
// positive value to expand
ListTile(
title: Text('Tile title'),
dense: true,
visualDensity: VisualDensity(vertical: 3), // to expand
onTap: () {
// tap actions
},
)
The values ranges from -4 to 4 and default is 0 as of writing this answer.
However, you cannot use this method for specific width or height size.
Just remove the Expanded Widget to avoid fill the space available and use a parent Container with a fixed height, the same as the itemExtent value:
Column(
children: <Widget>[
Container(
height: 100.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemExtent: 100.0,
itemCount: temp.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(temp[index]),
onTap: () {
print(temp[index]);
});
}),
),
Container(
child: Text('data'),
)
],
),
You should use a Container or Padding instead of ListTile if you need more customization.
You cannot set the height, but you can make it smaller by setting the dense property to true:
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(list[index].name,style: TextStyle(fontSize: 20.0),),
contentPadding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 16.0),
dense:true,
);
},
);
ListTile:
A single fixed-height row that typically contains some text as well as
a leading or trailing icon.
To be accessible, tappable leading and trailing widgets have to be at
least 48x48 in size. However, to adhere to the Material spec, trailing
and leading widgets in one-line ListTiles should visually be at most
32 (dense: true) or 40 (dense: false) in height, which may conflict
with the accessibility requirement.
For this reason, a one-line ListTile allows the height of leading and
trailing widgets to be constrained by the height of the ListTile. This
allows for the creation of tappable leading and trailing widgets that
are large enough, but it is up to the developer to ensure that their
widgets follow the Material spec.
https://api.flutter.dev/flutter/material/ListTile-class.html
Since there's no height property in ListTile you can limit the size of a tile by placing it inside a SizedBox:
SizedBox(
height: 32,
child: ListTile(..))

Flutter How to remove overscroll effect from ListView [duplicate]

By default, flutter adds a glowing effect on ListView/GridView/... to overscrolls on android phones
I would like to remove this effect entirely or on one specific scrollable.
I know that I can change ScrollPhysics to change between Bounce/Clamp. But this doesn't actually remove the glow effect.
What can I do ?
The glow effect comes from GlowingOverscrollIndicator added by ScrollBehavior
To remove this effect, you need to specify a custom ScrollBehavior. For that, simply wrap any given part of your application into a ScrollConfiguration with the desired ScrollBehavior.
The following ScrollBehavior will remove the glow effect entirely :
class MyBehavior extends ScrollBehavior {
#override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
To remove the glow on the whole application, you can add it right under MaterialApp :
MaterialApp(
builder: (context, child) {
return ScrollConfiguration(
behavior: MyBehavior(),
child: child,
);
},
home: new MyHomePage(),
);
To remove it on a specific ListView, instead wrap only the desired ListView :
ScrollConfiguration(
behavior: MyBehavior(),
child: ListView(
...
),
)
This is also valid if you want to change the effect. Like adding a fade when reaching borders of the scroll view.
The glow will disappear by changing the ListView's physics property to BouncingScrollPhysics to imitate the List behavior on iOS.
ListView.builder(
physics: BouncingScrollPhysics(),
}
The above solution did not work for me. I did this from another solution.
Wrap it with this widget to remove the shadow completely:
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (overscroll) {
overscroll.disallowGlow();
},
child: new ListView.builder(
//Your stuff here.
),
),
You can try BouncingScrollPhysics with all list or grid or scrollview:
//ScrollView:
SingleChildScrollView(
physics: BouncingScrollPhysics(),
)
//For ListView:
ListView.builder(
physics: BouncingScrollPhysics(),
}
//GridView
GridView.Builder(
physics: BouncingScrollPhysics(),
)
You can wrap your SingleChildScrollView or ListView.
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
return;
},
child: SingleChildScrollView()
)
Update on 2021
as buildViewportChrome is deprecated on March `21, we may have new way to implement this
A. Working Solution
class MyCustomScrollBehavior extends MaterialScrollBehavior {
#override
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
class MainApp extends StatelessWidget {
const MainApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
scrollBehavior: MyCustomScrollBehavior(),
title: 'App Title',
home: HomeUI(),
);
}
}
B. Explanation
By default, Flutter wraps any child widget into GlowingOverscrollIndicator as below code.
#override
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
switch (getPlatform(context)) {
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return child;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return GlowingOverscrollIndicator(
axisDirection: details.direction,
color: Theme.of(context).colorScheme.secondary,
child: child, // < ---------- our Child Widget is wrapped by Glowing Indicator
);
}
}
So we can easily override it, by directly return child without wrapping it to GlowingOverscrollIndicator
class MyCustomScrollBehavior extends MaterialScrollBehavior {
#override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
You don't need to build your own custom ScrollBehavior class. Instead, just wrap your scrollable widget in a ScrollConfiguration widget and set the behavior property to:
const ScrollBehavior().copyWith(overscroll: false).
Full code example:
ScrollConfiguration(
behavior: const ScrollBehavior().copyWith(overscroll: false),
child: PageView(
physics: const PageScrollPhysics(),
controller: model.pageController,
children: [
PageOne(),
PageTwo(),
PageThree(),
PageFour(),
],
),
),
try this work for me mybe work for you to
ScrollConfiguration(
behavior: new ScrollBehavior()..buildViewportChrome(context, null, AxisDirection.down),
child: SingleChildScrollView()
);
You can also try
SingleChildScrollView(
physics: ClampingScrollPhysics(),
)
If you migrated to null safety, you might get issues with the behavior. You can use this method that works with null safety:
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification? overscroll) {
overscroll!.disallowGlow();
return true;
},
child: child,
),
The currently accepted answer is outdated in the current version of Flutter.
Scroll behavior's ScrollBehavior.copyWith() method has an overscroll flag which can be set to false to avoid having to create your own ScrollBehavior class.
For example:
ScrollConfiguration(
behavior: MaterialScrollBehavior().copyWith(overscroll: false),
child : someScrollableWidget
)
`
It isn't good practice to just change the scroll behavior, as you may lose the native scrolling feel when running your app on different devices.
I have used below one for Scroll body without Scroll glow effect
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScrollConfiguration(
behavior: new ScrollBehavior()
..buildViewportChrome(context, null, AxisDirection.down),
child: SingleChildScrollView(
After Flutter 2.10 update Previous NotificationListener parameter code has been removed/deprecated.
New Code
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (overscroll) {
overscroll.disallowIndicator(); //previous code overscroll.disallowGlow();
return true;
},
child: ListView(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 15),
scrollDirection: Axis.horizontal,
children: List.generate(
items.length,
(index) => Padding(
padding: const EdgeInsets.only(right: 15),
child: AspectRatio(
aspectRatio: 13 / 9,
child:
LayoutBuilder(builder: (context, boxcon) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
boxShadow: const [
BoxShadow(
color: Colors.black12,
spreadRadius: 5,
blurRadius: 12)
],
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(items[index])),
color: greengradientcolor,
),
);
}),
))),
),
),

Flutter: How to put a CupertinoActivityIndicator into a customScrollView with SliverList

This is a mockup of what I want to achieve - it is a CupertinoActivityIndicator underneath a CupertinoSliverNavigationBar for notifying the user that the data is being downloaded.
Once it is downloaded, it should look like so:
Now, I have been trying to get this effect using the following code:
List<Trade> trades = [];
showLoadingDialog() {
return trades.length == 0;
}
getBody() {
if (showLoadingDialog()) {
return getProgressDialog();
} else {
return getTradeItemList();
}
}
getTradeItemList() {
return new CupertinoPageScaffold(
child: new CustomScrollView(slivers: <Widget>[
const CupertinoSliverNavigationBar(
largeTitle: const Text('Coffee Shop'),
),
getBody(),
]));
}
getProgressDialog() {
return new Container(
decoration: const BoxDecoration(
color: CupertinoColors.white,
),
child: new Center(child: const CupertinoActivityIndicator()));
}
However, I'm receiving this error because I'm trying to put a non-RenderSliver type into a Sliver. In other words, I'm putting in an CupertinoActivityIndicator into a Sliver and the code is rejecting it.
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════ The
following assertion was thrown building Container(bg:
BoxDecoration(color: Color(0xffffffff))): A RenderViewport expected a
child of type RenderSliver but received a child of type
RenderDecoratedBox. RenderObjects expect specific types of children
because they coordinate with their children during layout and paint.
For example, a RenderSliver cannot be the child of a RenderBox because
a RenderSliver does not understand the RenderBox layout protocol.
The closest I could get to achieving the effect I want is displayed in the gif below. However, as you can clearly see, the CupertinoSliverNavigationBar is not being displayed when the CupertinoActivityIndicator is visible. It is only after the data has been downloaded that the CupertinoSliverNavigationBar that says "Coffee Shop" is visible.
I achieved the above using the following code:
List<Trade> trades = [];
showLoadingDialog() {
return trades.length == 0;
}
getBody() {
if (showLoadingDialog()) {
return getProgressDialog();
} else {
return getTradeItemList();
}
}
getProgressDialog() {
return new Container(
decoration: const BoxDecoration(
color: CupertinoColors.white,
),
child: new Center(child: const CupertinoActivityIndicator()));
}
getTradeItemList() {
return new CupertinoPageScaffold(
child: new CustomScrollView(
slivers: <Widget>[
const CupertinoSliverNavigationBar(
largeTitle: const Text('Coffee Shop'),
),
new SliverPadding(
// Top media padding consumed by CupertinoSliverNavigationBar.
// Left/Right media padding consumed by Tab1RowItem.
padding: MediaQuery
.of(context)
.removePadding(
removeTop: true,
removeLeft: true,
removeRight: true,
)
.padding,
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(BuildContext context, int index) {
return new Tab1RowItem(
index: index,
lastItem: index == trades.length - 1,
color: "Coffee Beans",
colorName: "Buy coffee now",
);
},
childCount: trades.length,
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return getBody();
}
#override
void initState() {
super.initState();
loadDataTrades();
}
Can anyone tell me how I can achieve the effect I want?
Widget _mainFrame;
#override
Widget build(BuildContext context) {
return new CustomScrollView(
slivers: <Widget>[
new CupertinoSliverNavigationBar(
largeTitle: const Text("Coffe Shop"),
),
_mainFrame,
],
);
}
Widget _beforeDataLoaded() {
return new SliverFillRemaining(
child: new Container(
child: new Center(
child: new CupertinoActivityIndicator(),
),
),
);
}
Widget _dataLoadComplete() {
return new SliverList(
// Your list items
);
}
You change the _mainFrame Widget from the CupertionActivityIndicator to your listview if the load finished.