What is the alternative to RecyclerView in Flutter? - flutter

What is the alternative to Recycle view in flutter I have tried using this code
but how to do Animination with listview widget in flutter
Is this valid?
ListView(
children: <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
),
],
);

ListView:
Usually this should be used with a small number of children as the List will also construct the invisible elements in the list and a large amount of elements may render this inefficient.
ListView.builder():
The list items are constructed lazily, meaning only a specific number of list items are constructed and when a user scrolls ahead, the earlier ones are destroyed.
More info is here.

Following flutter-for/android-devs
The recommended, efficient, and effective way to build a list uses a
ListView.Builder. This method is great when you have a dynamic List or
a List with very large amounts of data. This is essentially the
equivalent of RecyclerView on Android, which automatically recycles
list elements for you:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sample App"),
),
body: ListView.builder(
itemCount: widgets.length,
itemBuilder: (BuildContext context, int position) {
return getRow(position);
}));
}
Widget getRow(int i) {
return GestureDetector(
child: Padding(
padding: EdgeInsets.all(10.0),
child: Text("Row $i")),
onTap: () {
setState(() {
widgets.add(getRow(widgets.length + 1));
print('row $i');
});
},
);
}

You can also use animatedlist widget for animations. code example are given in the following link.
AnimatedList

Related

flutter) I want to use a listview to jump directly to a specific section

As shown in the picture, I want to go directly to the corresponding list view when I press the button.
Instead of scrolling through the list, you can use the buttons to move left and right.
This is my current code.
As shown below, I am running a pageview called body (which changes briefly after using listview), and I know how to come out in order, but I don't know what to use to get it out of a specific number. Do you have a yes or another question?
GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => Choice821()),);
},
2
class Choice821 extends StatelessWidget {
#override
Widget build(BuildContext context) {
QuestionController _controller = Get.put(QuestionController());
return Scaffold(
appBar: AppBar(
title: Text('복습 시험', style: TextStyle(color: Colors.black, fontWeight:FontWeight.bold,fontSize: 20,),),
centerTitle: true,
elevation: 0,
),
body: Body(),
);
}
}
2
child: PageView.builder(
physics: NeverScrollableScrollPhysics(),
controller: _questionController.pageController,
onPageChanged: _questionController.updateTheQnNum,
itemCount: _questionController.questions.length,
itemBuilder: (context, index) => ayotube(
question: _questionController.questions[index],
id: _questionController.questionNumber.value,
),
),
You can simply do this:
// jump to page index with animation
_questionController.pageController.animateToPage(index);
// or jump to page index without animation
_questionController.pageController.jumpToPage(index);

how to Add some design at top after that listview with dynamic size list and then below some some design for advertisement and comment in flutter

Scaffold(
appBar: AppBar(
title: Text("Design test..."),
),
body: Container(
margin:EdgeInsets.fromLTRB(0, MediaQuery.of(context).padding.top, 0, 0
),
child: Column(
children: [
Container(//for Some Kind of design at top),
Column(
children: [
ListView.builder(
itemCount: listLength.length,
itemBuilder: (BuildContext buildContext, int index) {
return ListTile(title: Text("hello world")
);
}),
//i want to add some design here after the list view for advertisement and comment
],
),
],
),
),
);
my listview.builder() item length is dynamic so i want to expand my list view as much as it requied and when it ends i need some design just like youtube privious design where on the top video player after that video list and at the end comment part.thank you.
Yes you can achieve this, Refer to this code.
use the build method like this.
#override
Widget build(BuildContext context) {
return Scaffold(
body : ListView(
//Base Listview, it can be scrollable if content is large also
children:[
Container(
//Sample widget you can use your own
child:Text("Here is some design At Top")
),
ListView.builder(
//use shrinkWrap:true and physics:NeverScrollableScrollPhysics()
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: 10, //it can be dynamic and null checks can be appield,
itemBuilder: (context, index){
return Text("ListItem $index");
},
),
Container(
//Sample widget you can use your own
child: Text("Some Design for Ads")
),
Container(
//Sample widget you can use your own
child: Text("Some Design for Commentes")
)
]
)
);
}
Mark answer as right if it helped !!

NestedScrollView No Scroll when List is Short with Float SliverAppBar

I am having a ListView, that is required to use pull to refresh function, and a floating header is needed on the design. Therefore I have tried to use the NestedScrollView to fulfill the task. However, I find that even if the list is short, as the SliverAppBar is floating, the body is always a bit longer to make the list able to scroll to hide the app bar which is not what expected on the our design flow.
The design flow considered is to
pin the appbar (not able to scroll) when the body is shorter than the available space
able to float app bar when list body is longer than the available space
I have tried to listen the scroll notification, but it seems not work as what i want to obtain. Please give me some suggestions if there is any way can solve this problem. Thank you!
The following is the code so far i have tried:
return Scaffold(
body: Builder(
builder: (context, ) {
return SafeArea(
child: NotificationListener<ScrollNotification>(
onNotification: (info){
debugPrint('scroll = ${info.metrics.pixels}');
bool isFloat = info.metrics.pixels>57.0;
if(_isFloat!=isFloat){
_isFloat= isFloat;
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
setState((){});
});
}
return true;
},
child: NestedScrollView(
floatHeaderSlivers: false,
headerSliverBuilder: (context, isInnerScroll) {
return [
SliverAppBar(
title: Text('Demo'),
floating: _isFloat,
pinned: !_isFloat,
),
];
},
body: SmartRefresher(
controller: _refreshController,
onRefresh: () {
Future.delayed(Duration(milliseconds: 1000), () {
_refreshController.refreshCompleted();
});
},
child: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return ListTile(
title: Text('$index'),
);
},
),
),
),
),
);
}
),
);

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(..))

How can I put a SearchView on top of a ListView?

I'm new to flutter and am trying to stack a searchView on top of a ListView. I would Look something like this:
I don't know how to achieve this layout on flutter, i tried using a column(which crashes the app), used the a stack (which overlaps the widgets) and i finally tried to add a search widget a the first item of the ListView but that didn't result am looking for.
Widget build(BuildContext context) {
return new Scaffold(
drawer: _makeDrawer(),
appBar: new AppBar(
title: new Center(
child: new Text("translate"),
),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.people_outline), onPressed: () {})
],
),
body: _phraseListFutureBuilder(), // this part of the code renders the listview
);
}
FutureBuilder _phraseListFutureBuilder() {
return new FutureBuilder(
builder: (BuildContext context, AsyncSnapshot snapshot) {
return mPhrases.isEmpty
? new CircularProgressIndicator()
: _buildPhrases();
},
future: _fetchData());
}
A Column was the right choice, but you will also need an Expanded widget to specify which widget should fill the remaining space:
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
decoration: InputDecoration(
labelText: 'Search'
),
),
Expanded(
child: _phraseListFutureBuilder(),
)
],
);