I have a parent widget that contains multiple child widgets which each include a checkbox. How can I check every checkbox from the parent widget? - flutter

I have a parent widget that draws multiple child widgets using a listview. There is a checkbox within each of these child widgets. I am trying to implement a "select all" button in the parent widget which checks all of the children's checkboxes, but I'm having a hard time figuring out how to accomplish this.
Here is my parent widget:
class OrderDisplay extends StatefulWidget {
static const routeName = '/orderDisplay';
//final Order order;
//const OrderDisplay(this.order);
#override
OrderDisplayState createState() {
return OrderDisplayState();
}
}
class OrderDisplayState extends State<OrderDisplay> {
bool preChecked = false;
double total = 0;
List<OrderedItem> itemsToPayFor = [];
#override
Widget build(BuildContext context) {
final OrderDisplayArguments args =
ModalRoute.of(context).settings.arguments;
return Scaffold(
backgroundColor: MyColors.backgroundColor,
body: SafeArea(
child: Column(
children: [
Expanded(
child: SingleChildScrollView(
physics: ScrollPhysics(),
child: Container(
padding: EdgeInsets.only(top: 10),
child: Column(
children: [
Text(args.order.restaurantName,
style: MyTextStyles.headingStyle),
ListView.separated(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: args.order.orderedItems.length,
itemBuilder: (context, index) {
return FoodOrderNode(
preChecked, args.order.orderedItems[index],
onCheckedChanged: (isChecked) {
isChecked
? setState(() {
itemsToPayFor.add(
args.order.orderedItems[index]);
})
: setState(() {
itemsToPayFor.remove(
args.order.orderedItems[index]);
});
});
},
separatorBuilder: (context, index) =>
MyDividers.MyDivider)
],
)),
),
),
MyDividers.MyDivider,
Container(
height: 140,
color: MyColors.backgroundColor,
child: Row(children: [
Expanded(
flex: 5,
child: Column(
children: [
Expanded(flex: 2, child: SizedBox()),
Expanded(
flex: 6,
child: SelectAllButton(() {
print("SELECT ALL");
setState(() {
preChecked = true;
});
})),
Expanded(flex: 2, child: SizedBox())
],
)),
Expanded(
flex: 5,
child: Column(
children: [
Expanded(flex: 1, child: SizedBox()),
Expanded(
flex: 8,
child: PayNowButton(() {
print("PAY NOW");
},
double.parse(itemsToPayFor
.fold(0, (t, e) => t + e.itemPrice)
.toStringAsFixed(
2)))),
Expanded(flex: 1, child: SizedBox())
],
))
]))
],
)));
}
}
And here is FoodOrderNode:
typedef void SelectedCallback(bool isChecked);
class FoodOrderNode extends StatefulWidget {
final bool preChecked;
final OrderedItem item;
final SelectedCallback onCheckedChanged;
const FoodOrderNode(this.preChecked, this.item,
{#required this.onCheckedChanged});
#override
FoodOrderNodeState createState() {
return FoodOrderNodeState();
}
}
class FoodOrderNodeState extends State<FoodOrderNode> {
bool isChecked = false;
bool isSplitSelected = false;
#override
Widget build(BuildContext context) {
isChecked = widget.preChecked;
return Container(
height: 80,
padding: EdgeInsets.only(left: 15, right: 15),
decoration: BoxDecoration(
color: MyColors.nodeBackgroundColor,
),
child: Row(
children: [
Expanded(
flex: 1,
child: CircularCheckBox(
value: isChecked,
checkColor: Colors.white,
activeColor: Colors.blue,
autofocus: false,
onChanged: (bool value) {
print("Change to val: $value");
widget.onCheckedChanged(value);
setState(() {
isChecked = value;
});
},
)),
Expanded(
flex: 7,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.only(bottom: 5, left: 40),
child: Text(
widget.item.itemName,
style: TextStyle(fontSize: 18, color: Colors.black),
textAlign: TextAlign.left,
maxLines: 2,
overflow: TextOverflow.ellipsis,
)),
Container(
padding: EdgeInsets.only(left: 40),
child: Text(
"\$${widget.item.itemPrice}",
style:
TextStyle(fontSize: 16, color: MyColors.labelColor),
))
],
),
),
Expanded(
flex: 2,
child: isSplitSelected
? SplitButtonSelected(() {
setState(() {
isSplitSelected = false;
});
})
: SplitButtonUnselected(() {
setState(() {
isSplitSelected = true;
});
}))
],
),
);
}
}
I have tried creating a "preChecked" argument for FoodOrderNode and then using setState from the parent widget, however, that hasn't worked out. I have also tried using keys, but I couldn't figure out how to get those working for this either. Thank you, and let me know if you'd like any more relevant code.

Just put a global checkbox above the list items and give it isAllChecked (bool) on its value so when it will be checked set the state to isAllChecked => true and then in child checkboxes check for condition if isAllChecked is true then mark as true or checked.
GlobalCheckbox(
onChanged(value){
setState(()
{
isAllChecked==value;
});
}
);
ChildCheckBox(
value: isAllChecked ? true : false
)
this might help you:)

Related

Flutter - Provider is taking too long to change boolean variable

I am creating an app where i am using NotificationListener<UserScrollNotification> to change the boolean value on the basis of scroll direction... but when i scroll page for very first time all the content gets disappear for 2-3 seconds...I am using Provider.... Please help me...
Here i am trying to change boolean variable
NotificationListener<UserScrollNotification>(
onNotification: (notification) {
final ScrollDirection direction =
notification.direction;
if (direction == ScrollDirection.reverse) {
value.changeVisiblity(true);
} else if (direction ==
ScrollDirection.forward) {
value.changeVisiblity(false);
}
return false;
},
here is my provider class where boolean is defined
bool isVisible = false;
changeVisiblity(bool value) {
isVisible = value;
notifyListeners();
}
here is short video
Video
class SampleWidget extends StatelessWidget {
SampleWidget({Key? key}) : super(key: key);
final ValueNotifier<bool> isVisibility = ValueNotifier(false);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Expanded(
flex: 3,
child: ValueListenableBuilder(
valueListenable: isVisibility,
builder: (BuildContext context, bool value, Widget? child) {
return Column(
children: [
const Spacer(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: AnimatedCrossFade(
firstChild: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
children: [
value == false ? const Icon(Icons.food_bank_rounded) : const SizedBox(),
const Text("Food"),
],
),
Column(
children: [
value == false ? const Icon(Icons.people) : const SizedBox(),
const Text("Fashion"),
],
),
Column(
children: [
value == false ? const Icon(Icons.face) : const SizedBox(),
const Text("Beauty"),
],
),
],
),
secondChild: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text("Food"),
Text("Fashion"),
Text("Beauty"),
],
),
crossFadeState: value == false ? CrossFadeState.showFirst : CrossFadeState.showSecond,
duration: const Duration(milliseconds: 300),
)),
],
);
},
),
),
Expanded(
flex: 7,
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
if (index == 0) {
return VisibilityDetector(
onVisibilityChanged: (info) {
if (info.visibleFraction < 1) {
isVisibility.value = true;
} else {
isVisibility.value = false;
}
},
key: ValueKey(index),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("$index"),
),
);
} else {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text("$index"),
);
}
},
),
),
],
),
),
);
}
}

How to wait for a request to complete using ObservableFuture?

When I transition to a screen where I get a list of information via an API, it initially gives an error:
_CastError (Null check operator used on a null value)
and only after loading the information, the screen is displayed correctly.
I am declaring the variables like this:
#observable
ObservableFuture<Model?>? myKeys;
#action
getKeys() {
myKeys = repository.getKeys().asObservable();
}
How can I enter the page only after loading the information?
In button action I tried this but to no avail!
await Future.wait([controller.controller.getKeys()]);
Modular.to.pushNamed('/home');
This is the page where the error occurs momentarily, but a short time later, that is, when the api call occurs, the data appears on the screen.
class MyKeyPage extends StatefulWidget {
const MyKeyPage({Key? key}) : super(key: key);
#override
State<MyKeyPage> createState() => _MyKeyPageState();
}
class _MyKeyPageState
extends ModularState<MyKeyPage, KeyController> {
KeyController controller = Modular.get<KeyController>();
Widget countKeys() {
return FutureBuilder(
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
final count =
controller.myKeys?.value?.data!.length.toString();
if (snapshot.connectionState == ConnectionState.none &&
!snapshot.hasData) {
return Text('..');
}
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 1,
itemBuilder: (context, index) {
return Text(count.toString() + '/5');
});
},
future: controller.getCountKeys(),
);
}
#override
Widget build(BuildContext context) {
Size _size = MediaQuery.of(context).size;
return controller.getCountKeys() != "0"
? TesteScaffold(
removeHorizontalPadding: true,
onBackPressed: () => Modular.to.navigate('/exit'),
leadingIcon: ConstantsIcons.trn_arrow_left,
title: '',
child: Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(left: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Keys',
style: kHeaderH3Bold.copyWith(
color: kBluePrimaryTrinus,
),
),
countKeys(),
],
),
),
),
body: Observer(builder: (_) {
return Padding(
padding: const EdgeInsets.only(bottom: 81),
child: Container(
child: ListView.builder(
padding: EdgeInsets.only(
left: 12.0,
top: 2.0,
right: 12.0,
),
itemCount:
controller.myKeys?.value?.data!.length,
itemBuilder: (context, index) {
var typeKey = controller
.myKeys?.value?.data?[index].type
.toString();
var id =
controller.myKeys?.value?.data?[index].id;
final value = controller
.myKeys?.value?.data?[index].value
.toString();
return GestureDetector(
onTap: () {
.
.
},
child: CardMeyKeys(
typeKey: typeKey,
value: value!.length > 25
? value.substring(0, 25) + '...'
: value,
myKeys: pixController
.minhasChaves?.value?.data?[index].type
.toString(),
),
);
},
),
),
);
}),
bottomSheet: ....
)
: TesteScaffold(
removeHorizontalPadding: true,
onBackPressed: () => Modular.to.navigate('/exit'),
leadingIcon: ConstantsIcons.trn_arrow_left,
title: '',
child: Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(left: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'...',
style: kHeaderH3Bold.copyWith(
color: kBluePrimaryTrinus,
),
),
],
),
),
),
body: Padding(
padding: const EdgeInsets.only(bottom: 81),
child: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/images/Box.png',
fit: BoxFit.cover,
width: 82.75,
height: 80.91,
),
SizedBox(
height: 10,
),
],
),
), //Center
),
),
bottomSheet: ...
);
}
List<ReactionDisposer> disposers = [];
#override
void initState() {
super.initState();
controller.getKeys();
}
#override
void dispose() {
disposers.forEach((toDispose) => toDispose());
super.dispose();
}
}
Initially the error occurs in this block
value: value!.length > 25
? value.substring(0, 25) + '...'
: value,
_CastError (Null check operator used on a null value)
I appreciate if anyone can help me handle ObservableFuture correctly!
You need to call the "future" adding
Future.wait
(the return type of getKeys) keys=await Future.wait([
controller.getKeys();
]);
The problem is your getKeys function isn't returning anything, so there's nothing for your code to await. You need to return a future in order to await it.
Future<Model?> getKeys() {
myKeys = repository.getKeys().asObservable();
return myKeys!; // Presumably this isn't null anymore by this point.
}
...
await controller.controller.getKeys();
Modular.to.pushNamed('/home');

Flutter: Can't get container in SingleChildScrollView to extend vertically

I've spent the last 2 hours trying every method I could find (Expanded, IntrinsicHeight, BoxConstraints, etc) to try and get a container with a column of widget to extend to the full height. The container is inside a SingleChildScrollView because I need scrolling capabilities. This probably is part of the problem, but I can't seem to figure out why exactly.
This is the current behaviour:
This is the wanted behaviour:
This is my raw code:
class CreateNewArtikel extends StatefulWidget {
#override
_CreateNewArtikelState createState() => _CreateNewArtikelState();
}
class _CreateNewArtikelState extends State<CreateNewArtikel> {
final titleController = TextEditingController();
final subtitleController = TextEditingController();
final tagsController = TextEditingController();
final authorController = TextEditingController();
final textController = TextEditingController();
File imageFile;
#override
Widget build(BuildContext context) {
final isAdmin = Provider.of<bool>(context);
if (isAdmin == true) {
return GlobalScaffold(
body: SingleChildScrollView(
child: Container(
color: Colors.yellow,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GradientHeading(
large: true,
text: "Skapa ny artikel",
),
SizedBox(height: 15),
CustomTextFormField(
labelText: "Rubrik",
controller: titleController,
),
CustomTextFormField(
labelText: "Underrubrik",
controller: subtitleController,
),
CustomTextFormField(
labelText: "Tags",
controller: tagsController,
),
CustomTextFormField(
labelText: "Skriven av",
controller: authorController,
),
CustomTextFormField(
labelText: "Text",
controller: textController,
multiline: true,
),
imageFile != null
? NormalButton(
text: "Ta bort bild",
shouldOverideColor: true,
overriddenColor: redWarningColor,
onPressed: () {
imageFile = null;
setState(() {});
},
)
: NormalButton(
text: "Ladda upp bild",
outlined: true,
outlinedBgColor: primaryColor,
onPressed: () async {
imageFile = await ChooseImage()
.chooseImageFromGallery();
setState(() {});
},
),
imageFile != null
? Image(
image: FileImage(imageFile),
)
: Container(),
SizedBox(height: 40),
],
),
),
NormalButton(
text: "Skapa artikel",
onPressed: () async {
DatabaseService().createNewArtikel(
titleController.text,
subtitleController.text,
tagsController.text,
authorController.text,
textController.text,
imageFile,
);
Navigator.pop(context);
},
),
],
),
),
),
);
} else {
return GlobalScaffold(
body: Text("You don't have access to this page"),
);
}
}
}
Try this approach:
LayoutBuilder(
builder: (context, constraint) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraint.maxHeight),
child: IntrinsicHeight(
child: Column(
children: <Widget>[
Text("Header"),
Expanded(
child: Container(
color: Colors.red,
),
),
Text("Footer"),
],
),
),
),
);
},
)
For further information about this problem take a look at this discussion:
How to use Expanded in SingleChildScrollView?
Add the following to build()
final double hsize = MediaQuery.of(context).size.height;
final double pageHeight = hsize - kToolbarHeight -24;
(24 is the height of the statusbar in Android)
And add the following to your Container()
height: pageHeight

Update view in listview.builder child

I just started working with flutter, so far so good. But I have an issue at the moment:
I wish to make a check Icon visible when I tap on the child view in a Listview.builder widget
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
itemBuilder: (BuildContext context, int index){
// final item = feeds[index];
return FlatButton(
onPressed:(){
setState(() {
_selected = !_selected;
choosenUser = users[index];
print("the user:${users[index].fullName},$_selected");
});
},
child:(_selected) ? UserCard(users[index], _selected):UserCard(users[index], _selected)
);
}
)
inside UserCard there is a check Icon I wish to show or hide when the FlatButton in the ListView.builder is clicked.
I passed in a boolean to the UserCard but it does not work
class UserCard extends StatefulWidget{
UserItem userItem;
bool selected;
UserCard(this.userItem, this.selected);
#override
_UserCard createState() => _UserCard(userItem,selected);
}
class _UserCard extends State<UserCard>{
UserItem _userItem;
bool selected;
_UserCard(this._userItem, this.selected);
#override
Widget build(BuildContext context) {
// TODO: implement build
return /* GestureDetector(
onTap: () {
setState(() {
selected = !selected;
print("user:${_userItem.fullName}");
});
},
child:*/Container(
height:80 ,
child:
Column(
children: <Widget>[
Row(
children: <Widget>[
_userItem.profileUrl != null? CircleAvatar(child: Image.asset(_userItem.profileUrl),): Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: Colors.white70,
shape: BoxShape.circle,
image: DecorationImage(
image:AssetImage('assets/plus.png') //NetworkImage(renderUrl ??'assets/img.png')
)
),
),
SizedBox(width: 30,),
Expanded(
flex: 1,
child:
Container(
child:
Row(
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 12,),
_userItem.fullName != null? Text(_userItem.fullName, style: TextStyle(fontSize: 18)): Text('Anjelika Thompson', style: TextStyle(fontSize: 18),),
SizedBox(height: 12,),
Row(
//crossAxisAlignment: CrossAxisAlignment.start,
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(child: Icon(Icons.location_on),alignment: Alignment.topLeft,),
SizedBox(width: 10,),
_userItem.distance_KM.toString() != null ? Text(_userItem.distance_KM.toString()):Text('48.7 km')
]),
],
),
],
)
),
),
SizedBox(width: 0,),
selected ? Icon(Icons.check,color: Colors.red,size: 40,):SizedBox(child: Text('$selected'),)
],
),
Container(
height: 0.5,
color: Colors.grey,
)
],
) ,
// )
);
}
}
Please what am I doing wrong here
Save your selections in list of Boolean.
list<bool> selected = list<bool>();
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
itemBuilder: (BuildContext context, int index){
// final item = feeds[index];
return FlatButton(
onPressed:(){
setState(() {
selected[index] = !selected[index];
choosenUser = users[index];
print("the user:${users[index].fullName},$_selected");
});
},
child:UserCard(users[index], selected[index])
);
}
)
so I had to go a different route to fix the issue in my code. here is my code:
in my model class called UserItem, I introduced another parameter called selectedd
class UserItem{
String fullName, profileUrl;
double distance_KM;
bool selected;
UserItem(this.fullName, this.profileUrl, this.distance_KM, this.selected);
}
since am using static values for now, i passed in "false"
List<UserItem> users = []
..add(UserItem("Edward Norton","assets/profile_img.png", 12.0, false))
..add(UserItem("Gary Owen","assets/img.png", 21, false))
..add(UserItem("Eddie L.","assets/img_details.png", 12.7, false))
..add(UserItem("Carlos Snow","assets/header_user.png", 1.3, false))
..add(UserItem("Idibbia Olaiya","assets/profile_img.png", 0, false));
then when user clicks on any of the child item the selected value that was already set as false will be updated. here is my Listview.builder widget:
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
itemBuilder: (BuildContext context, int index){
// final item = feeds[index];
return
Stack(
children: <Widget>[
Container(
child: FlatButton(
onPressed:(){
setState(() {
selected = !selected;
users[index].selected =selected;
// _theIcon = selected ? _theIcon : Icon(Icons.check,color: Colors.grey,size: 40,);
choosenUser.add(users[index]) ;
// print("the user:${users[index].fullName},$selected");
// child_card(users[index], selected,index);
});
}, child:child_card(users[index]),
),
)
],
);
}
)
)
Widget child_card(UserItem user){
// print("the user:${user.fullName},$selected");
return UserCard(user);
}
Hope this helps someone.

Flutter display Listview when button pressed

List<ServicesMensCollection> menServicesList = []
..add(ServicesMensCollection('ihdgfstfyergjergdshf', 'janik', 10))
..add(ServicesMensCollection('ihdgfstfyergjerg', 'janik', 10))
..add(ServicesMensCollection('ihdgfstfyergjerg', 'janik', 10))
..add(ServicesMensCollection('ihdgfstfyergjergdf', 'janik', 10))
bool _value2 = false;
void _value2Changed(bool value) => setState(() => _value2 = value);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
body: new Container(
decoration: new BoxDecoration(color: const Color(0xFFEAEAEA)),
child: Padding(
padding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
child: Column(
children: <Widget>[
servicesCategory(),
],),),)); }
Widget servicesButton() {
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
onPressed: () {listView();},
child: Text('Mens'),),
RaisedButton(
onPressed: () {listView();},
child: Text('Womens')),
RaisedButton(
onPressed: () {listView();},
child: Text('Childrens'),
)]); }
Widget listView(){
return ListView.builder(
itemCount: menServicesList.length,
itemBuilder: (BuildContext context, int index) {
return list(index); },);
}
Widget list(int index){
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(menServicesList[index].name),
Text(menServicesList[index].name),
Checkbox(onChanged:_value2Changed,
value: _value2,
)],),);
}}
I am implementing listview with checkbox in my project.I have 3 buttons which is created in a row.I want to display the list when the button is clicked.Here the issue is listview is not at all visible for me.I had implemented the same example in android but i don't know how to do this in flutter.
Try this. This is a sample screen which you can refer for your implementation.
In this there are 3 sample list which are being replaced to main list on selection, you can add a function which will sort the list based on selection (so no need to have multiple lists)
import 'package:flutter/material.dart';
/*
These are the sample list for demo
*/
List<ItemVO> mainList = List();
List<ItemVO> sampleMenList = [
ItemVO("1", "Mens 1"),
ItemVO("2", "Mens 2"),
ItemVO("3", "Mens 3")
];
List<ItemVO> sampleWomenList = [
ItemVO("1", "Women 1"),
ItemVO("2", "Women 2"),
ItemVO("3", "Women 3")
];
List<ItemVO> sampleKidsList = [
ItemVO("1", "kids 1"),
ItemVO("2", "kids 2"),
ItemVO("3", "kids 3")
];
class TestScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _TestScreen();
}
}
class _TestScreen extends State<TestScreen> {
#override
void initState() {
super.initState();
mainList.addAll(sampleMenList);
}
#override
Widget build(BuildContext context) {
return Material(
child: Stack(
children: <Widget>[
ListView.builder(
itemBuilder: (BuildContext context, index) {
return getCard(index);
},
itemCount: mainList.length,
),
Container(
margin: EdgeInsets.only(bottom: 20),
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FloatingActionButton(
onPressed: () {
mainList.clear();
setState(() {
mainList.addAll(sampleMenList);
});
},
heroTag: "btn1",
child: Text("Mens"),
),
FloatingActionButton(
onPressed: () {
mainList.clear();
setState(() {
mainList.addAll(sampleWomenList);
});
},
heroTag: "btn2",
child: Text("Women"),
),
FloatingActionButton(
onPressed: () {
mainList.clear();
setState(() {
mainList.addAll(sampleKidsList);
});
},
heroTag: "btn3",
child: Text("Kids"),
)
],
),
),
],
),
);
}
/*
Get the card item for a list
*/
getCard(int position) {
ItemVO model = mainList[position];
return Card(
child: Container(
height: 50,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"ID:: "+model._id,
style: TextStyle(fontSize: 18, color: Colors.black),
),
Padding(padding: EdgeInsets.only(left: 5,right: 5)),
Text(
"Name:: "+model._name,
style: TextStyle(fontSize: 18, color: Colors.black),
)
],
),
),
margin: EdgeInsets.all(10),
);
}
}
/*
Custom model
i.e. for itemList
*/
class ItemVO {
String _id, _name;
String get id => _id;
set id(String value) {
_id = value;
}
get name => _name;
set name(value) {
_name = value;
}
ItemVO(this._id, this._name);
}
In your code you didn't added ListView in widget, so it will not show any list, so try adding ListView in widget and then change the list data and try it.
I think You have 2 choices on how to tackle your problem.
Preload the listViews and set their visibility to gone / invisible
Try to play around with the code from this blog