Onrefresh indicator is not working in conditional statement - dart

I have Scaffold which contains a body with condition to render different components. I have added onRefreshIndicator(). But it is not working when Text is rendered and working completely fine when list NamesList get rendered.
I have tried separating two components in different files but then also it is not working.
`body: Container(
child: RefreshIndicator(
child: fetched && names.length == 0
? Text('Not able to fetch')
: NamesList(names, widget.value, widget.header),
onRefresh: () => getJSONdata(widget.value),
),
)`
I expect that onRefreshIndicator() should work in both the condition.

Set your Container widget to have the max height available and put your Text widget inside a SingleChildScrollView with AlwaysScrollableScrollPhysics.
Container(
height: double.infinity,
child: RefreshIndicator(
child: fetched && names.length == 0
? SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Text("Not able to fetch"))
: NamesList(names, widget.value, widget.header),
onRefresh: () => getJSONdata(widget.value),
))

Related

Bottom padding after ListView.Builder

I have a Listview inside a bottom sheet .. like this:
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Directionality(
textDirection: globals.getDirection(),
child: Container(
margin: EdgeInsets.only(
right: 10.0,
left: 10.0),
height: MediaQuery.of(context).size.height / 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Flexible(
child: TextField()
),
Expanded(
child: ListView.builder(
shrinkWrap: false,
itemCount: nationalities.length,
itemBuilder: (BuildContext context, int index) {
return new Padding(
padding: EdgeInsets.only(top: 10.0),
child: GestureDetector(
onTap: () {
setState(() {
_data.nationality = nationalities[index];
});
Navigator.pop(context);
},
child: Text(
nationalities[index],
textAlign: TextAlign.center,
),
));
},
),
),
),
);
}
);
The problem that i have huge white space at the bottom i don't now from where it's coming .. as you can see from the screenshot:
How to remove this white space and make the listview expand in it instead?
Using an Expanded widget makes a child of a Row, Column, or Flex expand to fill the available space in the main axis (e.g., horizontally for a Row or vertically for a Column). If multiple children are expanded, the available space is divided among them according to the flex factor.
That's maybe your problem. Removing it may help you.
Next thing ...
Using a Flexible widget gives a child of a Row, Column, or Flex the flexibility to expand to fill the available space in the main axis (e.g., horizontally for a Row or vertically for a Column), but, unlike Expanded, Flexible does not require the child to fill the available space.
Next Thing:
By default, ListView will automatically pad the list's scrollable extremities to avoid partial obstructions indicated by MediaQuery's padding. To avoid this behavior, override with a zero padding property.
ListView(
padding: EdgeInsets.zero,
...);
Second Option
MediaQuery.removePadding(
context: context,
removeTop: true,
child: ListView(...),
)
Sorry for Exrta explanation ;
This is a bug that's caused by having a Flexible widget and an Expanded widget in the same Row/Column, https://github.com/flutter/flutter/issues/20575
You can fix it by removing the Flexible widget that's wrapping your TextField.
I faced the same issue when using ListView.builder() in ModalBottomSheet. I have to use Column instead of:
sortList() {
var itemList = <Widget>[
Text('1'),
Text('2'),
];
// for loop to add more items here
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: itemList);
}
Removing mainAxisSize: MainAxisSize.min will reproduce the issue.

ListView does not refresh whereas attached list does (Flutter)

I'm trying to get familiar with flutter and I'm facing some weird case. I want to build a dynamic ListView where a + button allows to add elements. I wrote the following State code:
class MyWidgetListState extends State<MyWidgetList> {
List<Widget> _objectList = <Widget>[
new Text('test'),
new Text('test')
];
void _addOne() {
setState(() {
_objectList.add(new Text('test'));
});
}
void _removeOne() {
setState(() {
_objectList.removeLast();
});
}
#override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new ListView(
shrinkWrap: true,
children: _objectList
),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new IconButton(
icon: new Icon(Icons.remove_circle),
iconSize: 36.0,
tooltip: 'Remove',
onPressed: _objectList.length > 2 ? _removeOne : null,
),
new IconButton(
icon: new Icon(Icons.add_circle),
iconSize: 36.0,
tooltip: 'Add',
onPressed: _addOne,
)
],
),
new Text(_objectList.length.toString())
],
);
}
}
My problem here is that the ListView is visually stuck with the 2 elements I initialized it with.
Internally the _objectList is well managed. For testing purpose I added a simple Text widget at the bottom that shows the size of the list. This one works fine when I click the Add/Remove buttons and it gets properly refreshed. Am I missing something?
Flutter is based around immutable data. Meaning that if the reference to an object didn't change, the content didn't either.
The problem is, in your case you always send to ListView the same array, and instead mutate its content. But this leads to ListView assuming the list didn't change and therefore prevent useless render.
You can change your setState to keep that in mind :
setState(() {
_objectList = List.from(_objectList)
..add(Text("foo"));
});
Another Solution!!
Replace ListView with ListView.builder
Code:
ListView.builder(
itemBuilder: (ctx, item) {
return _objectList[item];
},
shrinkWrap: true,
itemCount: _objectList.length,
),
Output:

Flutter - Showing suggestion list on top of other widgets

I am developing a screen where I have to show suggestions list below the textfield.
I want to achieve this
I have developed this so far
Following code shows textfield with suggestions in a list.
#override
Widget build(BuildContext context) {
final header = new Container(
height: 39.0,
padding: const EdgeInsets.only(left: 16.0, right: 2.0),
decoration: _textFieldBorderDecoration,
child: new Row(
children: <Widget>[
new Expanded(
child: new TextField(
maxLines: 1,
controller: _controller,
style: _textFieldTextStyle,
decoration:
const InputDecoration.collapsed(hintText: 'Enter location'),
onChanged: (v) {
_onTextChanged.add(v);
if (widget.onStartTyping != null) {
widget.onStartTyping();
}
},
),
),
new Container(
height: 32.0,
width: 32.0,
child: new InkWell(
child: new Icon(
Icons.clear,
size: 20.0,
color: const Color(0xFF7C7C7C),
),
borderRadius: new BorderRadius.circular(35.0),
onTap: (){
setState(() {
_controller.clear();
_places = [];
if (widget.onClearPressed != null) {
widget.onClearPressed();
}
});
},
),
),
],
),
);
if (_places.length > 0) {
final body = new Material(
elevation: 8.0,
child: new SingleChildScrollView(
child: new ListBody(
children: _places.map((p) {
return new InkWell(
child: new Container(
height: 38.0,
padding: const EdgeInsets.only(left: 16.0, right: 16.0),
alignment: Alignment.centerLeft,
decoration: _suggestionBorderDecoration,
child: new Text(
p.formattedAddress,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: _suggestionTextStyle,
),
),
onTap: () {
_getPlaceDetail(p);
},
);
}).toList(growable: false),
),
),
);
return new Container(
child: new Column(
children: <Widget>[header, body],
),
);
} else {
return new Container(
child: new Column(
children: <Widget>[header],
),
);
}
}
Header(Textfield) and body(Suggestions List - SingleChildScrollView with ListBody) is wrapped inside the Column widget, and column expands based on the total height of the children.
Now the problem is as Column expands, layout system pushes other widgets on screen to the bottom. But I want other widgets to stay on their positions but suggestion list starts to appear on top of other widgets.
How can I show suggestions list on top of other widgets? And the suggestions list is dynamic, as user types I call the Google Places API and update the suggestions list.
I have seen there is showMenu<T>() method with RelativeRect positions but it doesn't fulfills my purpose, my suggestion list is dynamic(changing based on user input) and the styling for each item I have is different from what PopupMenuItem provides.
There is one possibility I can think of using Stack widget as root widget of this screen and arrange everything by absolute position and I put suggestion list as a last child of the stack children list. But it is not the right solution I believe.
What other possibilities I need to look into? What other Widgets can be used here in this use-case?
And again use-case is simple, overlaying suggestion list on other widgets on the screen and when user tap any of the item from the list then hiding this overlaid suggestion list.
The reason why your autocomplete list pushes down the widgets below it is because the List is being expanded on the Container. You can use Flutter's Autocomplete widget and it should inflate the autocomplete list over other widgets.
var fruits = ['Apple', 'Banana', 'Mango', 'Orange'];
_autoCompleteTextField() {
return Autocomplete(
optionsBuilder: (TextEditingValue textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<String>.empty();
}
return fruits.where((String option) {
return option
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
},
onSelected: (String selection) {
debugPrint('You just selected $selection');
},
);
}

Flutter: Banner Ad Overlapping The Main Screen

I am doing a Flutter app and managed to show the AdMob banner ad, however the ad overlaps the bottom of my app's main screen:
By following this article, I managed to make the app screen's bottom properly displayed, but the persistentFooterButtons is sacrificed, which I think is not an ideal solution.
I am thinking about putting the Scaffold object and a fixed height area into a column that is contained by a Center object, something similar to the following:
#override
Widget build(BuildContext context) {
return new Center(
child: new Column (
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded (
child: _getScaffold(),
),
new Expanded (
child: new Container(height: 50.0,)
)
],
),
);
}
But in this way I get the exception "A RenderFlex overflowed by 228 pixels on the bottom":
Anybody can show me how to build such layout? I want every component of my scaffold properly displayed, with a fixed height dummy footer that is ok to be overlapped by the Admob's banner ad.
Any help is much welcome.
Jimmy
Also we can add some trick like bottomNavigationBar under the Scaffold
bottomNavigationBar: Container(
height: 50.0,
color: Colors.white,
),
This will take floating button up.
Finally I got it:
#override
Widget build(BuildContext context) {
return new Center(
child: new Column (
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Expanded (
child: _getScaffold(),
),
new Container(height: 50.0,
child: new Placeholder(color:Colors.blue))
],
),
);
}
The trick is Expanded here is for the Scaffold only, but for the dummy footer just a fixed height Container is required. Now I can display everything available from the Scaffold object.
Layout building of Flutter sometimes really confuses me...
If I understand your question well, I think you want to have your ad shown from the bottom while using a FAB. I think using a Stack widget here is a good solution, I created this example in a rush but should be enough to show you what I mean:
class AdBar extends StatefulWidget {
#override
_AdBarState createState() => new _AdBarState();
}
class _AdBarState extends State<AdBar> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: new ListView(
children: new List.generate(50, (int index) {
return new Text("widgets$index");
}),
),
persistentFooterButtons:
<Widget>[
new Stack(
children: <Widget>[
new Container (
color: Colors.transparent,
child: new Material(
color: Colors.cyanAccent,
child: new InkWell(
onTap: () {
},
child: new Container(
//color: Colors.cyanAccent,
width: MediaQuery
.of(context)
.size
.width * 0.90,
height: MediaQuery
.of(context)
.size
.height * 0.25,
),
),),),
new Positioned(
right: 0.0,
child: new FloatingActionButton(
onPressed: () {}, child: new Icon(Icons.fastfood)))
],
)
]
);
}
}

flutter implement sticky headers and the snap to item effect

For the last few days, I've been reading through flutter framework documentation and especially the sliver part but I'm not quite sure where to start.
I'm trying to implement the sticky headers and snap effect.
Might the RenderSliverList be a good start? Do I need to re-layout things? Do I need to do additional drawing? And if so where?
Any help on where to start would be a huge help, thanks in advance!
Edit: I think I understood the layout part now, but I just can't find where the painting is supposed to happen.
Edit 2: For clarification, this is the desired "sticky header effect":
How can I make sticky headers in RecyclerView? (Without external lib)
and this is the "snap" effect:
https://rubensousa.github.io/2016/08/recyclerviewsnap
For the "sticky header effect" I ran into this problem myself, so I created this package to manage sticky headers with slivers: https://github.com/letsar/flutter_sticky_header
To use it you have to create one SliverStickyHeader per section in a CustomScrollView.
One section can be wrote like this:
new SliverStickyHeader(
header: new Container(
height: 60.0,
color: Colors.lightBlue,
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: new Text(
'Header #0',
style: const TextStyle(color: Colors.white),
),
),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(context, i) => new ListTile(
leading: new CircleAvatar(
child: new Text('0'),
),
title: new Text('List tile #$i'),
),
childCount: 4,
),
),
);
If you want, the entire source code for the above demo is here: https://github.com/letsar/flutter_sticky_header/blob/master/example/lib/main.dart
I hope this will help you.
It's dead simple :
Use a CustomScrollView and give it as child both a SliverList and a SliverAppBar. You may replace the SliverList with a SliverGrid if you need to.
Then, depending on the effect you want to achieve, there are a few properties you may set on SliverAppBar:
snap
expandedHeight (+ flexibleSpace)
floating
pinned
In the end, you may have something similar to :
new CustomScrollView(
slivers: <Widget>[
new SliverAppBar(
title: new Text("Title"),
snap: true,
floating: true,
),
new SliverFixedExtentList(
itemExtent: 50.0,
delegate: new SliverChildBuilderDelegate(
(BuildContext context, int index) {
return new Container(
alignment: Alignment.center,
color: Colors.lightBlue[100 * (index % 9)],
child: new Text('list item $index'),
);
},
),
),
],
)
Even better, you can concatenate different scroll behaviour inside a single CustomScrollView.
Which means you can potentially have a grid followed by a list just by adding a SliverGrid as a child to your scrollView.
I know I know, flutter is awesome.
I managed to do the stickyheader effect on Flutter for an iOS app using the following code - credit goes to this piece of code written here from where I drew my inspiration (https://github.com/flutter/flutter/blob/master/examples/flutter_gallery/lib/demo/animation/home.dart#L112):
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate({
#required this.collapsedHeight,
#required this.expandedHeight,}
);
final double expandedHeight;
final double collapsedHeight;
#override double get minExtent => collapsedHeight;
#override double get maxExtent => math.max(expandedHeight, minExtent);
#override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return new Container(color: Colors.red,
child: new Padding(
padding: const EdgeInsets.only(
left: 8.0, top: 8.0, bottom: 8.0, right: 8.0),
child: new Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new Text("Time"), new Text("Price"), new Text("Hotness")
],
),
)
);
}
#override
bool shouldRebuild(#checked _SliverAppBarDelegate oldDelegate) {
return expandedHeight != oldDelegate.expandedHeight
|| collapsedHeight != oldDelegate.collapsedHeight;
}
}
To make it sticky, add the _SliverAppBarDelegate to the silvers widget list:
new SliverPersistentHeader(delegate: new _SliverAppBarDelegate(collapsedHeight: 36.0, expandedHeight: 36.0), pinned: true, ),
I'm not really sure how to make the _SliverAppBarDelegate wrap the content though, I had to provide it with a size of 36 logical pixels to get it to work. If anyone know how it could just wrap content, please drop a comment to the answer below.
I solved this problem, try sticky_and_expandable_list.
Features
Support build an expandable ListView, which can expand/collapse section or create sticky section header.
Use it with CustomScrollView、SliverAppBar.
Listen the scroll offset of current sticky header, current sticky header index and switching header index.
Only use one list widget, so it supports large data and a small memory usage.
More section customization support, you can return a new section widget by sectionBuilder, to customize background,expand/collapse animation, section layout, and so on.
Support add divider.
As per documentation, you can place a StickyHeader or StickyHeaderBuilder inside any scrollable content.
The documentation page provides only an example how to apply a StickyHeader with a ListView, ok what about the other widgets such as SingleChildScrollView or CustomScrollView ?
In this example I will provide a very simple StickyHeader with a SingleChildScrollView and sure you can put it inside any SingleChildScrollView you want:
return Container(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("My title"),
StickyHeader(
header: Container(
child: // Put here whatever widget you like as the sticky widget
),
content: Column(
children: [
Container(
child: // Put here whatever widget you like as scrolling content (Column, Text, ListView, etc...)
),
],
),
),
],
),
),
);
without implementing yours using sliver, you can achieve this using flutter community awesome plugin.
https://pub.dev/packages/sticky_headers

Resources