Can I random to show SizeBox widget? - flutter

I want to show SizeBox widget by random. when I open this class it should be random to show Size Box 1 first or Size Box 2 first.
class Page extends StatelessWidget {
var random = new Random();
int randomNumber;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
randomNumber = random.nextInt(1);
if(randomNumber == 1){
/////////////////////////////////////// Size box 1 ////////////////////////////////////
SizedBox(
child: TextButton(
onPressed: () {
AlertDialog(
title: Text('a'),
content: Text('a'));
},
child: Image.asset('images/test.jpg'),
)),
}else{
/////////////////////////////////////// Size box 2 ////////////////////////////////////
SizedBox(
child: TextButton(
onPressed: () {
AlertDialog(
title: Text('b'),
content: Text('b'));
},
child: Image.asset('images/test2.jpg'),
)),
}
I try to use randomNumber = random.nextInt(1) in children: <Widget>[] but it show
The element type 'int' can't be assigned to the list type 'Widget'.dart(list_element_type_not_assignable)
It seems I cannot write dart code in widget. Can I random to show SizeBox widget ?

The error occurs because you called randomNumber = random.nextInt(1); inside the Row children. Since randomNumber is of type int and not of type Widget you can't do this. One way to fix this is to create a StatefulWidget and set the randomNumber in initState method.
By the way using if/else inside children of Row/Column you don't put the curly brackets {}.
import 'package:flutter/material.dart';
import 'dart:math';
class Page extends StatefulWidget {
#override
_Page createState() => _Page();
}
class _Page extends State<Page> {
var random = new Random();
int randomNumber;
#override
void initState(){
randomNumber = random.nextInt(1);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
if (randomNumber == 1)
/////////////////////////////////////// Size box 1 ////////////////////////////////////
SizedBox(
child: TextButton(
onPressed: () {
AlertDialog(title: Text('a'), content: Text('a'));
},
child: Image.asset('images/test.jpg'),
),
)
else
/////////////////////////////////////// Size box 2 ////////////////////////////////////
SizedBox(
child: TextButton(
onPressed: () {
AlertDialog(title: Text('b'), content: Text('b'));
},
child: Image.asset('images/test2.jpg'),
),
),
],
),
),
],
),
),
);
}
}

Related

Flutter : I want to change an image when you tap the image, and others are not affected by the tap

I am creating a simple app in Flutter. There are 7 images on 1 screen. I need a function that you can change an image when you tap one of the images. However, now when I tap an image, the other 6 images are also changed. I made a variable "isReal" to put into buildButton() and "isReal" would be switched true and false in the For statement which switch "isReal" in buildButton(). But, that did not work. Could you give me some advice on this problem? Thank you.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
class Screen extends StatefulWidget {
#override
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
bool isReal = true;
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.teal[100],
// appBar: AppBar(
// title: Text('AnimalSounds'), backgroundColor: Colors.teal),
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
buildButton('cat.mp3', Colors.red, 'images/cat.png',
'images/cat_real.jpg'),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
buildButton('dog.mp3', Colors.yellow, 'images/dog.png',
'images/cow.png'),
buildButton('cow.mp3', Colors.orange, 'images/cow.png',
'images/dog.png'),
])),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
buildButton('pig.mp3', Colors.green, 'images/pig.png',
'images/elephant.png'),
buildButton('elephant.mp3', Colors.teal,
'images/elephant.png', 'images/rooster.png'),
buildButton('rooster.mp3', Colors.blue,
'images/rooster.png', 'images/pig.png'),
])),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
buildButton('goat.mp3', Colors.purple, 'images/goat.jpg',
'images/pig.png'),
],
)),
],
),
)));
}
Expanded buildButton(sound, color, simpleImage, realImage) {
return Expanded(
child: FlatButton(
onPressed: () {
setState(() {
isReal = !isReal;
});
final player = AudioCache();
player.play(sound);
},
color: color,
child: isReal ? Image.asset(simpleImage) : Image.asset(realImage),
));
}
}
Ok, you have variable isReal that is the same for entire class (i.e. each button use the same variable). So when you change it's value by tapping on one button it affects all other buttons as well.
To solve this issue I would recommend to move button implementation into a separate Statefull widget. This way you can keep your Screen class as Stateless.
UPD:
Obviously you should watch some tutorials on how to make this on your own. But just for this time this is how it should look like after you separate widgets.
What I did here is:
Create new widget class FlipButton
Move code from your method into build function of new widget
Add parameters to constructor
This way when each FlipButton will have it's own isReal variable.
NOTE: I didn't try to compile it so there might be some errors.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
class Screen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.teal[100],
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
//replace all occurances on `buildButton` method with new widget
FlipButton(sound: 'cat.mp3', color: Colors.red, simpleImage: 'images/cat.png', realImage: 'images/cat_real.jpg'),
Expanded(
child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[
FlipButton(sound: 'dog.mp3', color: Colors.yellow, simpleImage: 'images/dog.png', realImage: 'images/cow.png'),
FlipButton(sound: 'cow.mp3', color: Colors.orange, simpleImage: 'images/cow.png', realImage: 'images/dog.png'),
])),
Expanded(
child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[
FlipButton(sound: 'pig.mp3', color: Colors.green, simpleImage: 'images/pig.png', realImage: 'images/elephant.png'),
FlipButton(sound: 'elephant.mp3', color: Colors.teal, simpleImage: 'images/elephant.png', realImage: 'images/rooster.png'),
FlipButton(sound: 'rooster.mp3', color: Colors.blue, simpleImage: 'images/rooster.png', realImage: 'images/pig.png'),
])),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
FlipButton(sound: 'goat.mp3', color: Colors.purple, simpleImage: 'images/goat.jpg', realImage: 'images/pig.png'),
],
)),
],
),
),
),
);
}
}
/// You can copy this widget into separate file for better formatting
///
class FlipButton extends StatefulWidget {
//declare final variables
final String sound;
final Color color;
final String simpleImage;
final String realImage;
//constructor for this class
const FlipButton({
Key? key,
required this.sound,
required this.color,
required this.simpleImage,
required this.realImage,
}) : super(key: key);
#override
_FlipButtonState createState() => _FlipButtonState();
}
class _FlipButtonState extends State<FlipButton> {
//inside the state declare variable that is about to change
bool isReal = false;
#override
Widget build(BuildContext context) {
return Expanded(
child: FlatButton(
onPressed: () {
setState(() {
isReal = !isReal;
});
final player = AudioCache();
player.play(sound);
},
color: widget.color,
child: isReal ? Image.asset(widget.simpleImage) : Image.asset(widget.realImage),
));
}
}
You can use Random class from dart:math to generate the next random image.
Exemple :
int imageNumber = 1;
void updateImage() {
setState(() {
//Random.nextInt(n) returns random integer from 0 to n-1
imageNumber = Random().nextInt(7) + 1;
});
}
#override
Widget build(BuildContext context) {
return Center(
child: Expanded(
child: Padding(
padding: const EdgeInsets.all(50.0),
child: FlatButton(
child: Image.asset('images/dice$imageNumber.png'),
onPressed: () {
updateImage();
},
),
),
),
);
}

setState not updating

I just can't figure out what is the problem with this set state method in flutter. Everything seems okay. But the text is not updating on onPressed.
class NetBalanceWidget extends StatefulWidget {
#override
_NetBalanceWidgetState createState() => _NetBalanceWidgetState();
}
class _NetBalanceWidgetState extends State<NetBalanceWidget> {
#override
Widget build(BuildContext context) {
String text = 'NetBalance-Amount';
return RawMaterialButton(
onPressed: () {
setState(() {
text = 'It works';
});
},
child: Container(
height: 80.0,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(text),
Text('0.00'),
],
),
),
),
);
}
}
You have text as a local variable in the build method. setState is essentially just calling build again, and is resetting the value of text back to its default of 'NetBalance-Amount'.
Move its declaration outside of build:
class _NetBalanceWidgetState extends State<NetBalanceWidget> {
String text = 'NetBalance-Amount';
#override
Widget build(BuildContext context) {
return RawMaterialButton(
onPressed: () {
setState(() {
text = 'It works';
});
},
child: Container(
height: 80.0,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(text),
Text('0.00'),
],
),
),
),
);
}
}

Having an issue passing button titles to another screen in dart

In short I am trying to pass the title of the button from my input screen to my calculator model and once inside the calculator model, a value will be returned based on the button selected. However, currently my calculator is preforming the task WITHOUT waiting for the title of the button. Any ideas on how I can await the button title? I tried future, async, and await functionality but still couldn't get it to work properly.
Input Screen
class InputScreen extends StatefulWidget {
#override
_InputScreenState createState() =>
_InputScreenState();
}
class _InputScreenState
extends State<InputScreen> {
final MyButton selected = MyButton(title3: 'Female', title4: 'Male', title5: 'Unknown');
#override
void dispose() {
super.dispose();
selected.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Column(
children: <Widget>[
ClipPath(
clipper: MyClipper(),
child: Container(
height: 250,
width: double.infinity,
decoration: BoxDecoration(
gradient: kHeaderGradient,
image: DecorationImage(
image: AssetImage('images/virus.png'),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
Navigator.pop(context);
}),
],
title: Text(
'Gender Multiplier',
style: kHeaderTextStyle,
),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
],
),
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ValueListenableBuilder<Option>(
valueListenable: selected,
builder: (context, option, _) => MakeButtons(
num0: 3,
num1: 6,
makeButtonWidth: MediaQuery.of(context).size.width * 0.45,
selected: option,
onChanged: (newOption) => selected.option = newOption,
),
),
RoundedButton(
title: 'Calculate',
onPressed: () {
Calculator calc;
calc = Calculator(
buttonTitle: selected.title,
);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ResultsScreen(
genderMultiplier: calc.calculate(),
),
),
);
},
),
],
),
],
),
);
}
}
class MyClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var path = Path();
path.lineTo(0, size.height - 80);
path.quadraticBezierTo(
size.width / 2, size.height, size.width, size.height - 80);
path.lineTo(size.width, 0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return false;
}
}
Calculator model
class Calculator {
Calculator({
this.buttonTitle,
});
String buttonTitle;
double _genderModifier
String calculate() {
double getMultiplier() {
if (buttonTitle == 'Male') {return 2;}
else if (buttonTitle == 'Female') {return 1;}
else {return 0;}
}
if (getMultiplier() == 0) {return 'Does not work';} else {
_genderModifier = 10 * getMultipler();
return _genderModifier.toStringAsFixed(1);}
}
}
Results Screen
class ResultsScreen extends StatelessWidget {
ResultsScreen({
#required this.genderMultiplier,
});
final String genderMultiplier;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CALCULATOR'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
padding: EdgeInsets.all(15),
alignment: Alignment.bottomLeft,
child: Text(
'Your Result',
),
),
ReuseableCard(
bgColor: kGreyBackgroundColor,
cardChild: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
genderMultiplier,
),
],
),
),
RoundedButton(
title: 'Re-Calc',
onPressed: () {
Navigator.pop(context);
},
)
],
),
);
}
}
You are using a widget called ValueListenableBuilder and it seems you do not really know what it does. And I cannot really help you with the specifics of your code there because I don't know what a MyButton is or what MakeButtons does. It looks complicated.
But as a matter of fact you don't need to know how that widget works, because I don't see any reason why you would use it in your code in the first place.
If in doubt, go with simple. Simple and working is way better than complicated and not working.
Take your calculator class, this is all it really does:
String calculate(String buttonTitle) {
if (buttonTitle == 'Male') return 20.toStringAsFixed(1);
if (buttonTitle == 'Female') return 10.toStringAsFixed(1);
return 'Does not work';
}
Try to not over-complicate things.
If you need a three-state selection, why not go with radio buttons? Simple, easy, tutorials all over the internet. That should work. Or use ToggleButtons.

how to adjust the container as per the device screen in flutter

my app look like below
once logged in, in home page it has 3 tabs, and also a bottom navigation bar, and a app bar.
below the tab bar there is a container it contain many cards. I have given a fixed height to container, but when I checked in multiple devices there is a issue , i.e for the container having cards, getting overflow.
I tried to take the entire screen height then took the 70% for the container , but in phones with smaller resolution its showing overflow, if I adjusted as per that screen , In bigger screen , container takes very less space and more than 20% of space is wasted.
I am adding my code below,
here is my dashboard.dart code: ===>
import './generate_report_list.dart';
import './provider_classes.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:bmnav/bmnav.dart' as bmnav;
import './dashboard_view.dart';
class DashBoard extends StatefulWidget {
#override
_DashBoardState createState() => _DashBoardState();
}
class _DashBoardState extends State<DashBoard> with WidgetsBindingObserver {
int _currentIndex = 0;
Widget _view;
double maxHeight;
double maxWidth;
double maxCardWidth;
List<String> headers = ['Dashboard', 'Reports List', 'Profile', 'Settings'];
List<IconData> icons = [
Icons.dashboard,
Icons.insert_chart,
Icons.account_circle,
Icons.settings,
];
List<String> images = [
('assets/dashboard.png'),
('assets/growth.png'),
('assets/user.png'),
('assets/settings.png'),
];
getView(int index) {
List<Widget> _viewList = <Widget>[
GenerateReportList(),
GenerateReportList(),
GenerateReportList(),
GenerateReportList(),
];
setState(() {
_view = _viewList[index];
_currentIndex = index;
Provider.of<ScreenHeader>(context)
.setScreenHeader(headers[_currentIndex]);
});
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
#override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
#override
Widget build(BuildContext context) {
String appBarHeader = Provider.of<ScreenHeader>(context).getScreenHeader();
maxWidth = MediaQuery.of(context).size.width;
maxCardWidth = maxWidth / 2;
return Scaffold(
appBar: AppBar(
title: Text(
(appBarHeader ?? 'Dashboard'),
),
centerTitle: true,
),
body: _view ?? DashBoardView(),
bottomNavigationBar: bmnav.BottomNav(
onTap: (index) {
getView(index);
},
labelStyle: bmnav.LabelStyle(visible: true),
iconStyle:
bmnav.IconStyle(color: Colors.black, onSelectColor: Colors.red),
elevation: 10,
items: [
bmnav.BottomNavItem(Icons.home, label: 'Dashboard'),
bmnav.BottomNavItem(Icons.trending_up, label: 'Reports'),
bmnav.BottomNavItem(Icons.person, label: 'Profile'),
bmnav.BottomNavItem(Icons.settings, label: 'Settings')
],
),
);
}
}
generate_report_list.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:developer' as developer;
class GenerateReportList extends StatefulWidget {
#override
_GenerateReportListState createState() => _GenerateReportListState();
}
class _GenerateReportListState extends State<GenerateReportList>
with SingleTickerProviderStateMixin {
Future reportList;
List<String> typesOfReports = [];
String currentReportSummaryType;
TabController _tabController;
#override
void initState() {
super.initState();
currentReportSummaryType = 'detailed';
_tabController = TabController(vsync: this, length: 3);
}
void _handleTabSelection(var index) {
developer
.log("index: array:" + typesOfReports[0] + "," + typesOfReports[1]);
setState(() {
print("index is " + index);
if (index == 0) {
currentReportSummaryType = "Group A";
} else if (index == 1) {
currentReportSummaryType = "Group B";
} else if (index == 2) {
currentReportSummaryType = "Group C";
}
});
}
getBody() {
double maxHeight = MediaQuery.of(context).size.height;
developer.log('Max height:' + maxHeight.toString());
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: [
Container(
child: TabBar(
labelColor: Colors.black,
tabs: <Widget>[
new Tab(text: 'Group A', icon: new Icon(Icons.list)),
new Tab(text: 'Group B', icon: new Icon(Icons.pie_chart)),
new Tab(text: 'Group C', icon: new Icon(Icons.insert_chart)),
],
controller: _tabController,
onTap: _handleTabSelection,
),
),
SingleChildScrollView(
child: Container(
margin: new EdgeInsets.all(0.0),
height: (maxHeight * 0.60),
child: SingleChildScrollView(
child:new Center(
child: Column(
children: <Widget>[
cardGen(),
cardGen(),
cardGen(),
cardGen(),
cardGen(),
cardGen(),
],
)))))
],
));
}
cardGen() {
return Card(
child: Container(
height: (MediaQuery.of(context).size.height * 0.6) * 0.25,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("sample"),
Text("dummy"),
],
),
],
),
),
);
}
createCard(BuildContext context) {
double maxHeight = MediaQuery.of(context).size.height;
Container(
height: (maxHeight * 0.6) * 0.25,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("sample"),
Text("dummy"),
],
),
],
),
);
}
#override
Widget build(BuildContext context) {
return getBody();
}
}
provider_classes.dart
import 'package:flutter/material.dart';
class ScreenHeader with ChangeNotifier {
String _screenHeader;
getScreenHeader() => _screenHeader;
setScreenHeader(String newHeader) {
_screenHeader = newHeader;
notifyListeners();
}
}
provider classes is just for displaying the data in appbar.
In dashboard.dart I am creating a appbar,and bottomsheet, and in generate_report_list I am adding 3 new tabs , for each tab once clicked I am displaying the cards.
How to assign the height to container carrying card so that it should fit on every device.,and how can I add scrollable to the tabs , i.e group A, group B, Group C.
Thanks
Change:
Column(
children: <Widget>[
cardGen(),
...
To:
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
cardGen(),
...

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