Ad
Click On Grid Element To Show More Elements Flutter
I have a list of contacts, wondering how to show only the first 5 and the 6ed element to be "show more" element which when clicked on would show the rest of the contacts.
I'm looking for advice on how to achieve this UI functional:
Ad
Answer
Solution:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class Contact {
final String name;
Contact(this.name);
}
class ContactsPage extends StatefulWidget {
@override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
final contacts = [
Contact("sahar"),
Contact("Joe"),
Contact("fo"),
Contact("Fifo"),
Contact("Moshe"),
];
var _displayAll = false;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("contacts"),),
backgroundColor: Colors.white,
body: Center(
child:_gridContacts(),
),
);
}
Widget _gridContacts() {
final size = _displayAll ? contacts.length : contacts.length - 2;
final contactsWidget = List.generate(
size, (index) => _contactItem(contacts[index]))
..add(_seeNoSeeMore());
return GridView.count(
crossAxisCount: 3,
childAspectRatio: 2/1,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
children: contactsWidget,);
}
Widget _contactItem(Contact item) {
return Container(
color: Colors.blue.withOpacity(0.5),
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.person),
Text(item.name),
],
),
);
}
Widget _seeNoSeeMore() {
return InkWell(
onTap: ()=>setState(()=>_displayAll = !_displayAll),
child: Container(
color: Colors.blue.withOpacity(0.5),
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.person),
Text(_displayAll?"hide":"Show all"),
],
),
),
);
}
}
Notice: for better performance don't use setState instead use state management or the native one streambuilder.
Ad
source: stackoverflow.com
Related Questions
- → How do you create a 12 or 24 mnemonics code for multiple cryptocurrencies (ETH, BTC and so on..)
- → Flutter: input text field don't work properly in a simple example..... where am I wrong?
- → Can I customize the code formatting of Dart code in Atom?
- → Is it possible to develop iOS apps with Flutter on a Linux virtual machine?
- → Display SnackBar in Flutter
- → JSON ObjectMapper in Flutter
- → Material flutter app source code
- → TabBarSelection No such method error
- → How do I set the animation color of a LinearProgressIndicator?
- → Add different routes/screens to Flutter app
- → Is there a way to get the size of an existing widget?
- → How to share a file using flutter
- → Is there an easy way to find particular text built from RichText in a Flutter test?
Ad