Plotting a drop-down menu with a list of cards - flutter

In my flutter project, I want to plot a dropdown list first and then a list of Cards.
Like the above picture, I want to keep a dropdown menu with list of items("All, Visited, Pending, Cancelled") below the appbar and the "All" option selected by default. Below the dropdown box, I want to plot a list of cards.
My main aim is to select the card according to the selected item in the dropdown box. If I select the Pending option from the dropdown then below the cards with only Pending status will be shown. If I choose All option from the dropdown then all of the cards will be shown.
I want to choose the cards according to the dropdown's items.
I have written the code for plotting a list of cards but unable to find out the way to write the code for dropdown menu. Kindly help me plotting the dropdown box (below the appbar & before the cards).
Here is my code for the list of cards:
import 'package:flutter/material.dart';
class AdminHomeContent extends StatefulWidget {
#override
_AdminHomeContentState createState() => _AdminHomeContentState();
}
class _AdminHomeContentState extends State<AdminHomeContent> {
Color getdynamicColor(String status) {
if(status == "Pending"){
return Colors.lightGreen;
}
if (status == "Visited") {
return Colors.green[900];
}
if (status == "Cancelled") {
return Colors.red;
}
return Colors.black;
}
final List<Patient> patients = [
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true),
Patient('Person B', 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTF8fGh1bWFufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80',
8, 5, 'Cancelled', '23-12-2019', false),
Patient('Person C', 'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 7, 'Visited', '01-02-2019', false),
Patient('Person D', 'https://upload.wikimedia.org/wikipedia/commons/e/ec/Woman_7.jpg',
8, 4, 'Pending', '20-09-2018', true),
Patient('Person E', 'https://cdn.pixabay.com/photo/2017/08/07/14/15/portrait-2604283__340.jpg',
8, 6, 'Visited', '28-04-2017', false)
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: aapBarSection('Today\'s Appointments' , Colors.blueAccent[700], context),
body:
Container(
margin: EdgeInsets.only(top: 60.0),
child: ListView.builder(
itemCount: patients.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(9.0),
child: SizedBox(
height: 120,
child: Card(
elevation: 5.0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Row(
children: [
Expanded(
flex: 3,
child: Container(
child: CircleAvatar(
backgroundImage: NetworkImage(patients[index].imgPath),
radius: 40.0,
),
),
),
Expanded(
flex: 4,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(patients[index].name, style: TextStyle(
fontSize: 23.0,
fontWeight: FontWeight.bold,
color: Colors.black87
),),
SizedBox(
height: 20,
),
Text(patients[index].completedSession.toString() +'/'+ patients[index].totalSession.toString(),
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
color: Colors.black54
),),
],
),
),
),
Expanded(
flex: 3,
child: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Container(
height: 10,
width: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: getdynamicColor(patients[index].status)
),
),
SizedBox(
width: 8.0,
),
Text(patients[index].status,
style: TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold,
color: getdynamicColor(patients[index].status)
),
),
],
),
),
),
],
),
),
),
),
),
);
},
),
),
);
}
}
Here is my model class:
patient.dart
class Patient {
String name ;
String imgPath ;
int totalSession ;
int completedSession ;
String status ;
String dob ;
bool isActive ;
Patient(this.name, this.imgPath,this.totalSession,this.completedSession,this.status,this.dob,this.isActive);
}

Use ExpansionTile , its Easy
ExpansionTile(
initiallyExpanded: false,
title: Text(
"Settings",
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w700,
color: Colors.white),
),
children: <Widget>[
Container(
color: Colors.grey[100],
child: Column(
children: [
ListTile(
title: Text(
'Charges',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w500,
color: Colors.black87),
),
onTap: () {},
),
Divider(
color: Colors.grey[600],
),
ListTile(
title: Text(
'Billing',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w500,
color: Colors.black87),
),
onTap: () {},
),
Divider(
color: Colors.grey[600],
),
ListTile(
title: Text(
'Notice',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.w500,
color: Colors.black87),
),
onTap: () {},
),
],
),

Related

Flutter App Screen is appearing weird on Samsung S8

Image is here
Flutter app screen and text is appearing weird in Samsung S8 mobile
but tested in Other Samsung devises and its working fine, you can see how its supposed to work on the other devices on the above image
any one know why is this screen issue is happening only on samsung s8 ,only this image is here no log is getting so it is hard to resolve , is anyone faced this issue before,
minimumSdk is 21
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:splink/src/constants/app_colors.dart';
import 'package:splink/src/controllers/login_view_controllers.dart';
import 'package:splink/src/view/login_view/login_welcome_view.dart';
import 'package:splink/src/view/signup_view/signup_welcome_view.dart';
class LandingView extends StatefulWidget {
const LandingView({Key? key}) : super(key: key);
#override
State<LandingView> createState() => _LandingViewState();
}
class _LandingViewState extends State<LandingView> {
final signLoginController = Get.find<LoginViewController>();
final controller = PageController(
viewportFraction: 1,
keepPage: true,
);
List items = [
"assets/images/6D2Lmtv_X8A.png",
"assets/images/secondimage.png",
"assets/images/thirdImage.png"
];
List textItems = [
//first page of intro
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text(
"Find and play sports at",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
Text(
"anywhere, anytime",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
SizedBox(
height: 25,
),
Text(
"splink helps you find, connect and organise activities",
style: TextStyle(
color: Colors.white,
),
),
Text(
"with other sports players easily at anywhere, anytime",
style: TextStyle(
color: Colors.white,
),
),
],
),
//second page of intro
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text(
"Organise and manage",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
Text(
"activties easily",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
SizedBox(
height: 25,
),
Text(
"no more messy groups and missed activities.",
style: TextStyle(
color: Colors.white,
),
),
Text(
"Activity creation and RSVPs, calendar-tracking",
style: TextStyle(
color: Colors.white,
),
),
Text(
"or notifications, everything doe easily in-app",
style: TextStyle(
color: Colors.white,
),
),
],
),
//third page of intro
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text(
"Meet, play and endorse",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
Text(
"one another",
style: TextStyle(
fontSize: 28, color: Colors.white, fontWeight: FontWeight.bold),
),
SizedBox(
height: 25,
),
Text(
"Have fun, encourage one another by exchanging medals,",
style: TextStyle(
color: Colors.white,
),
),
Text(
"track sports statistics and keep on playing!",
style: TextStyle(
color: Colors.white,
),
),
],
),
];
#override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
final pages = List.generate(
3,
(index) => Image.asset(
items[index],
fit: BoxFit.cover,
),
);
final pages2 = List.generate(3, (index) => textItems[index]);
return Scaffold(
backgroundColor: primaryColor,
body: Column(
children: [
Expanded(
child: ClipPath(
clipper: ClipPathClass(),
child: PageView.builder(
controller: controller,
padEnds: false,
// itemCount: pages.length,
itemBuilder: (_, index) {
return SizedBox(
height: size.height,
width: size.width,
child: pages[index % pages.length]);
},
onPageChanged: (value) {
signLoginController.curouselIndex(value % pages.length);
},
),
),
),
Expanded(
child: Container(
color: primaryColor,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
child: SmoothPageIndicator(
controller: controller,
count: 3,
effect: const ExpandingDotsEffect(
strokeWidth: 2.0,
dotColor: Colors.white,
activeDotColor: Colors.white,
dotHeight: 6,
dotWidth: 6,
),
),
),
const SizedBox(
height: 15,
),
Obx(
() => textItems[signLoginController.curouselIndex.value],
),
const SizedBox(
height: 70,
),
Padding(
padding: const EdgeInsets.only(right: 15, left: 15),
child: Material(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
child: InkWell(
onTap: () {
Get.to(SignupWelcomeView());
},
borderRadius: BorderRadius.circular(15),
child: Container(
width: size.width,
height: 50,
alignment: Alignment.center,
child: Text(
'Sign Up',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: primaryColor),
),
),
),
),
),
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.only(right: 15, left: 15),
child: InkWell(
onTap: () {
Get.to(LoginWelcomeView());
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(color: Colors.white),
),
width: size.width,
height: 50,
alignment: Alignment.center,
child: const Text(
'Login',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: Colors.white),
),
),
),
),
],
),
),
)
],
),
);
}
}
class ClipPathClass extends CustomClipper<Path> {
#override
Path getClip(Size size) {
Path path = Path();
path.addOval(Rect.fromCircle(
center: Offset(size.width * 0.5, -10),
radius: size.height - 20,
));
return path;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
I mean, the "issue" is that the width/pixel density of the device is causing the text to overflow to the next line. You can either use a FittedBox, or tweak the fontSize to optimize it depending on the width (using MediaQuery or LayoutBuilder), both sould work.
You can also align the text on the center, instead of to the right, and I'd add some padding to ensure the text doesn't go right up to the screen border.
How do I auto scale down a font in a Text widget to fit the max number of lines?

Setting Height on Grid Tile Bar

I have a general question regarding the height of a GridTile Bar.
I currently have the GridTile display like this:
My Objective is to have it like this:
When I add the SizedBox to leave a space between price and Address, the address gets cut off the second line.
Any Ideas on how to move it up.
Here is my code of the Grid Tile:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../providers/listing.dart';
class ListingItem extends StatelessWidget {
#override
Widget build(BuildContext context) {
final listing = Provider.of<Listing>(context, listen: false);
final formatDolar = new NumberFormat("#,##0.00", "en_US");
return ClipRRect(
borderRadius: BorderRadius.circular(10),
child: GridTile(
child: GestureDetector(
onTap: () {},
child: Image.network(
listing.coverPhoto,
fit: BoxFit.cover,
),
),
header: GridTileBar(
title: Text(''),
trailing: IconButton(
icon: Icon(Icons.favorite_border),
color: Theme.of(context).accentColor,
onPressed: () {},
),
),
footer: GridTileBar(
backgroundColor: Colors.black54,
title: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'\$ ${formatDolar.format(listing.price)}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
SizedBox(
width: 20,
height: 5,
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Flexible(
child: Text(
'${listing.street}, ${listing.street2}, ${listing.city}, ${listing.state}, ${listing.zipCode}',
maxLines: 3,
style: TextStyle(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w500),
),
),
SizedBox(
height: 5,
),
Text(
'|',
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 5,
),
Text(
'${listing.bedRooms} bds',
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 5,
),
Text(
'|',
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 5,
),
Text(
'${listing.bathRooms} bth',
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 5,
),
],
),
),
SizedBox(
height: 1,
),
],
),
),
),
);
}
}
and here it is the code for the Grid:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/listings.dart';
import './listing_item.dart';
class ListingGrid extends StatelessWidget {
#override
Widget build(BuildContext context) {
final listingData = Provider.of<Listings>(context);
final listings = listingData.items;
return GridView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: 10,
itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
value: listings[i],
child: ListingItem(),
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
childAspectRatio: 3.5 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10),
);
}
}
I have tried changing the childAspectRatio in the grid but I only get the cover photo to get bigger not the Tile Bar which is what I want to move up.
Any Ideas?
Kind Regards.
Put GridTileBar widget in a Container widget and give it the height that you want. Here's an example code:
GridTile(
footer: Container(
padding: const EdgeInsets.all(8),
color: Colors.black54,
height: 60,
child: GridTileBar(
title: Text(
"Example",
style: TextStyle(color: Colors.black),
),
),
),

'RenderBox was not laid out' error even after using Expanded

I have added two card widgets in a row enclosed in a columnCode:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Padding(
padding: EdgeInsets.fromLTRB(0.0, 10, 0.0, 0.0),
child: Row(
children: [
Expanded(
child: SizedBox(
height: 70,
child: Card(
color: Colors.orange[500],
child: ListTile(
leading: CircleAvatar(
backgroundImage:
AssetImage('assets/card_photo.png'),
),
title: Text(
'Teacher of the month',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins-Bold'),
),
subtitle: Text(
'MAY 2020',
style: TextStyle(
fontSize: 8,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Poppins-Bold'),
),
onTap: () {},
),
),
),
),
Expanded(
child: SizedBox(
height: 70,
child: Card(
color: Colors.orange[500],
child: ListTile(
leading: CircleAvatar(
backgroundImage:
AssetImage('assets/card_photo.png'),
),
title: Text(
'Teacher of the month',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins-Bold'),
),
subtitle: Text(
'CLASS NAME',
style: TextStyle(
fontSize: 8,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Poppins-Bold'),
),
onTap: () {},
),
),
),
),
],
),
),
],
),
),
);
}
}
This is the output:Output Image
However I want this row to be scrollabe widgets of cards. But even after using expanded, I am getting 'RenderBox was not laid out' error.
Here is the code for it:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Padding(
padding: EdgeInsets.fromLTRB(0.0, 10, 0.0, 0.0),
child: SingleChildScrollView(//added scrollview widget
scrollDirection: Axis.horizontal,
child: Row(
children: [
Expanded(
child: SizedBox(
height: 70,
child: Card(
color: Colors.orange[500],
child: ListTile(
leading: CircleAvatar(
backgroundImage:
AssetImage('assets/card_photo.png'),
),
title: Text(
'Teacher of the month',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins-Bold'),
),
subtitle: Text(
'MAY 2020',
style: TextStyle(
fontSize: 8,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Poppins-Bold'),
),
onTap: () {},
),
),
),
),
Expanded(
child: SizedBox(
height: 70,
child: Card(
color: Colors.orange[500],
child: ListTile(
leading: CircleAvatar(
backgroundImage:
AssetImage('assets/card_photo.png'),
),
title: Text(
'Teacher of the month',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
fontFamily: 'Poppins-Bold'),
),
subtitle: Text(
'CLASS NAME',
style: TextStyle(
fontSize: 8,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Poppins-Bold'),
),
onTap: () {},
),
),
),
),
],
),
),
),
],
),
),
);
}
}
Edit: I also want text below the icon. If someone could help me with that also. Sample image name icon
Check if this works
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class something extends StatelessWidget {
#override
Widget build(BuildContext context) {
var appBar = AppBar();
return Container(
height: MediaQuery.of(context).size.height / 3,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: 6,
itemExtent: MediaQuery.of(context).size.height / 3,
itemBuilder: (context, index) {
return _cards(context, appBar);
},
),
);
}
}
Widget _cards(BuildContext context, AppBar appBar) {
return Align(
child: Container(
height: 100,
child: Card(
semanticContainer: true,
clipBehavior: Clip.antiAliasWithSaveLayer,
elevation: 5,
margin: EdgeInsets.all(10),
color: Colors.orange[500],
child: ListTile(
leading: Column(
children: [
CircleAvatar(
backgroundImage: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
),
Text("Name"),
],
),
title: Text('Teacher of the month', style: _textStyle(10)),
subtitle: Text('MAY 2020', style: _textStyle(8)),
onTap: () {},
),
),
),
);
}
_textStyle(double size) {
return TextStyle(
fontSize: size,
fontWeight: FontWeight.bold,
color: Colors.white,
fontFamily: 'Poppins-Bold');
}
It gives me output like this
You should use listView widget.
ListView(
children: <Widget>[
ItemOne(),
ItemTwo(),
ItemThree(),
],
),
and to change the scroll physics use:
scrollDirection: Axis.horizontal,

How to make dynamic listview in tabbar

I want to make here Listing of cicrleavater, and in that cicleavter size issue width not getting more than 20 ! i want to make listing like instagram stories...and each tap i want show same pages but data differnt and current circle avater border need to show yello color....! how to do that i show you my screen size issue top whre cicleavter size issue i want make dyanamic listview and show on border when i tapped on it it
class FolderPageTabBAr extends StatefulWidget {
#override
_FolderPageTabBArState createState() => _FolderPageTabBArState();
}
class _FolderPageTabBArState extends State<FolderPageTabBAr> {
List<Widget> pages = [
CampaignFolder(),
ShelfScreen(),
CampaignFolder(),
ShelfScreen(),
];
double Redius = 40.0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: pages.length,
initialIndex: 0,
child: Scaffold(
body: Stack(
children: <Widget>[
TabBarView(
children: pages,
),
Container(
margin: EdgeInsets.only(top: 110,left: 1),
child: SizedBox(
height: 80,
width: 500,
child: TabBar(
tabs: [
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
radius: 22,
backgroundImage: NetworkImage(Globals.PhotographerProf),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
Globals.Buisnessname,
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 11.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Family",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 10.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
"Album",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 9.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
],
unselectedLabelColor: Colors.orange,
labelColor: Colors.deepOrange,
indicatorColor: Colors.transparent,
),
)
),
],
),
),
);
}
}
To create multiple (dynamic) views that look similar use List View Builder
FULL Example:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyClass {
final String url;
final int id;
MyClass(this.url, this.id);
}
class Foo extends StatefulWidget {
#override
State<StatefulWidget> createState() => FooState();
}
class FooState extends State<Foo> {
int selectedIndex = 0;
List<MyClass> items = [
MyClass('https://picsum.photos/250?image=9', 1),
MyClass('https://picsum.photos/250?image=10', 5),
MyClass('https://picsum.photos/250?image=11', 33)
];
#override
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
height: 90,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
});
},
child: getAvatarView(items[index], index == selectedIndex),
);
},
),
),
Text(
"here is my page for id ${items[selectedIndex].id}",
style: TextStyle(backgroundColor: Colors.black, color: Colors.red),
),
],
),
);
}
Widget getAvatarView(MyClass item, bool isSelected) {
return Container(
margin: isSelected ? const EdgeInsets.all(5.0) : null,
decoration: BoxDecoration(
border: isSelected ? Border.all(color: Colors.yellow) : null),
child: Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(item.url),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
);
}
}
To pass multiple attributes in an item (callback function, url for img,...) use a List of Custom classes.

How can I Loop through data that is stored in my sharedpreference with a key in - Flutter

This is the function that helps me get the data from my shared preference storage:
var user;
var userData;
var anchors;
#override
void initState() {
_getUserAnchor();
super.initState();
}
_getUserAnchor() async{
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
anchors = user['Anchors'];
print(anchors);
setState(() {
userData = anchors;
});
}
This is the widget that is supposed to display the data:
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: NavDrawer(),
appBar: AppBar(
title: Text('Dashboard'),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
backgroundColor: Colors.white,
body: Container(
padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
child: ListView(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(Icons.card_membership,
size: 35, color: Colors.orange[400]),
Text(
'Assigned Anchors',
style: TextStyle(color: Colors.orange[400], fontSize: 25),
),
Icon(Icons.notifications_none, size: 35, color: Colors.white)
],
),
Column(
children: persons.map((p) {
return personDetailCard(p); //this is where I want to display the data
}).toList())
],
),
),
);
}
this is how the json array is looking in the shared preferences after successful login:
{
"Anchors": [
{
"Oid": 11,
"Name": "MAIZE ASSOCIATION OF NIGERIA",
"Acronym": "MAAN",
"DistributionCentres": [
{
"Oid": 11,
"Name": "Logo Centre (Zone A)",
"Address": "Private Warehouse, Ugba, Logo LGA"
},
{
"Oid": 12,
"Name": "Makurdi Centre (Zone B)",
"Address": "Ministry of Agric, Makurdi "
},
{
"Oid": 13,
"Name": "Oturkpo Centre (Zone C)",
"Address": "Private Warehouse, Oturkpo"
},
{
"Oid": 15,
"Name": "Borno MAAN centre",
"Address": "Bolori Store, Flavour Mill, Behind Vita Foam, Maiduguri"
}
]
},
{
"Oid": 2,
"Name": "MAIZE GROWERS, PROCESSORS AND MARKETERS ASSOCIATION OF NIGERIA",
"Acronym": "MAGPAMAN",
"DistributionCentres": [
{
"Oid": 2,
"Name": "Guma Centre",
"Address": "P 32, 2nd Avenue Federal Housing Estate, N/Bank, Makurdi"
},
{
"Oid": 3,
"Name": "Logo Centre",
"Address": "Terhemen Akema Storage Facility, Ugba, Logo LGA"
},
{
"Oid": 5,
"Name": "Oturkpo Centre",
"Address": "Grain Store, Lower Benue Okele Project, Otukpo"
},
{
"Oid": 6,
"Name": "Gboko Centre",
"Address": "K3 New Road, Opposite former coca cola plant. Solar Schools Street, Gboko"
},
{
"Oid": 7,
"Name": "Gwer East Centre",
"Address": "Ahua Shardye's Warehouse, Behind Sylkan Filling Station, Ikpayongo , G/East LGA"
},
{
"Oid": 8,
"Name": "Kwande Centre",
"Address": "KM 3, Adagi Road, Adikpo"
},
{
"Oid": 9,
"Name": "Ohimini Centre",
"Address": "Ajoga Oglewu, Ohimini"
},
{
"Oid": 10,
"Name": "Oju Centre",
"Address": "Behind Town Hall, Ohuhu owo, Oju LGA"
}
]
}
]
}
so I want to display the name, the acronym, and count DistributionCentres but I don't know how to go about it. can somebody help me? I am using shared preferences because there are numbers anchors assigned to a logged-in user. Initially, I was able to do this by hard-coding an array within the file but I couldn't achieve the same with shared preference. please can someone help me? Please. If it works so I will get rid of the hard-coded Person Array object.
Here's the overall page view below:
import 'package:erg_app/StockPage.dart';
import 'package:erg_app/models/users_model.dart';
import 'package:flutter/material.dart';
import 'package:erg_app/Widgets/nav-drawer.dart';
import 'package:erg_app/models/eopmodel.dart';
import 'package:erg_app/StartScan.dart';
import 'dart:convert';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MaterialApp(
home: EopPage(),
));
class EopPage extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<EopPage> {
List<Person> persons = [
Person(
name: 'RIFAN',
profileImg: 'assets/images/user.png',
allocated_farmers: "300",
validated_farmers: "345",
non_validated_farmers: "120",
daily_inventory_status: "Completed",
distribution_centers: "100"),
Person(
name: 'MAAN',
profileImg: 'assets/images/user.png',
allocated_farmers: "230",
validated_farmers: "195",
non_validated_farmers: "110",
daily_inventory_status: "Incompleted",
distribution_centers: "70"),
Person(
name: 'COPMAN',
profileImg: 'assets/images/user.png',
allocated_farmers: "560",
validated_farmers: "45",
non_validated_farmers: "780",
daily_inventory_status: "Completed",
distribution_centers: "40"),
];
Widget personDetailCard(Person) {
return Container(
padding: const EdgeInsets.all(10.0),
////////////// 1st card///////////
child: Card(
elevation: 4.0,
color: Colors.grey[100],
margin: EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 10),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
child: Container(
padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 50.0,
height: 50.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.cover,
image: AssetImage(Person.profileImg)))),
),
SizedBox(
width: 20,
),
Text(
Person.name,
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 20,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
],
),
Container(width: 10),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Allocated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 70, top: 12),
child: Text(
Person.allocated_farmers,
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 70, top: 12),
child: Text(
Person.validated_farmers,
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Non Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 40, top: 12),
child: Text(
Person.non_validated_farmers,
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Distribution Centers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 60, top: 12),
child: Text(
Person.distribution_centers,
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Daily Inventory Status:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 50, top: 12),
child: Text(
Person.daily_inventory_status,
textAlign: TextAlign.left,
style: TextStyle(
color: Person.daily_inventory_status == 'Completed'
? Colors.green
: Colors.red,
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Container(
height: 20,
),
Row(
children: <Widget>[
/////////// Buttons /////////////
Padding(
padding: const EdgeInsets.all(10.0),
child: Person.daily_inventory_status == 'Completed'
? FlatButton(
child: Padding(
padding: EdgeInsets.only(
top: 8, bottom: 8, left: 10, right: 10),
child: Text(
'Validate Farmer',
textDirection: TextDirection.ltr,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.green,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(20.0)),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => StartScanPage()));
// Edit()was here
},
)
: FlatButton(
child: Padding(
padding: EdgeInsets.only(
top: 8, bottom: 8, left: 10, right: 8),
child: Text(
'Take Inventory',
textDirection: TextDirection.ltr,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.blueGrey,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(20.0)),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => StockPage()));
},
),
),
/////////// End of Buttons /////////////
],
),
],
),
),
),
);
}
var user;
var userData;
var anchors;
#override
void initState() {
_getUserAnchor();
super.initState();
}
_getUserAnchor() async{
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
anchors = user['Anchors'];
print(anchors);
setState(() {
userData = anchors;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: NavDrawer(),
appBar: AppBar(
title: Text('Dashboard'),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
backgroundColor: Colors.white,
body: Container(
padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
child: ListView(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Icon(Icons.card_membership,
size: 35, color: Colors.orange[400]),
Text(
'Assigned Anchors',
style: TextStyle(color: Colors.orange[400], fontSize: 25),
),
Icon(Icons.notifications_none, size: 35, color: Colors.white)
],
),
Column(
children: persons.map((p) {
return personDetailCard(p);
}).toList())
],
),
),
);
}
}
Here is an example for you to achieve your scenario..
var user;
var userData;
List anchors = [];
_getUserAnchor() async{
SharedPreferences localStorage = await SharedPreferences.getInstance();
user = userJson;
setState(() {
anchors = user['Anchors'];
});
print(anchors);
setState(() {
userData = anchors;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('test'),),
body: Column(
children: <Widget>[
ListView.builder(
shrinkWrap: true,
itemCount: anchors.length,
itemBuilder: (BuildContext context, int i){
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Column(
children: <Widget>[
Text(anchors[i]['Name']),
Text(anchors[i]['Oid'].toString()),
],
),
),
);
})
],
),
);
}
Here I didn't get data from shared preferences i have equal your json to userJson, U can use your same steps get the data from shared preferences and follow up, So you can build list of card's.. hope this will help you...