Insert value textfield to format Map in flutter when get loop - flutter

how to insert value textfield controller in looping condition, I want to create new textfield when the button 'Tambah' have presse, but there is problem when I check criemHistories value, this is my code
class _TestingState extends State<Testing> {
int textFieldCount = 1;
List<Map<String, String>> crimeHistories = [];
List<Widget> buildTextFields() {
List<Widget> textFields = [];
for (int i = 0; i < textFieldCount; i++) {
TextEditingController pengadilanC = TextEditingController();
TextEditingController polresC = TextEditingController();
Map<String, String> crimeHistory = {
"court": pengadilanC.text,
"police_department": polresC.text,
};
crimeHistories.add(crimeHistory);
textFields.add(Column(
children: [
Container(
margin: EdgeInsets.only(top: 20),
child: Column(
children: [
Row(
children: [
Expanded(
flex: 3,
child: RichText(
text: TextSpan(
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
text: 'Pengadilan Negeri',
),
),
),
Expanded(
flex: 7,
child: Align(
alignment: Alignment.center,
child: TextField(
controller: pengadilanC,
onChanged: (value) {
crimeHistory["court"] = value;
},
),
),
),
],
),
],
),
),
Container(
margin: EdgeInsets.only(top: 20),
child: Column(
children: [
Row(
children: [
Expanded(
flex: 3,
child: RichText(
text: TextSpan(
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
text: 'Polres/Polsek',
),
),
),
Expanded(
flex: 7,
child: Align(
alignment: Alignment.center,
child: TextField(
controller: polresC,
onChanged: (value) {
crimeHistory["police_department"] = value;
},
),
),
),
],
),
],
),
),
],
));
// Masukkan Map ke dalam list crimeHistories
}
return textFields;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Column(children: buildTextFields()),
ElevatedButton(
child: Text('Tambah'),
onPressed: () {
textFieldCount++;
},
),
ElevatedButton(
child: Text('Remove'),
onPressed: () {
setState(() {
textFieldCount--;
});
},
),
ElevatedButton(
child: Text("Simpan"),
onPressed: () {
print(crimeHistories);
},
),
],
),
);
}
}
this code can run and add form textfield properly, but when I check crimeHistories value, there is 3 data list, how come it's can be happend? and how to solve it?

Related

How to make custom month picker for reusable in flutter

I want to create a reusable WidgetMonthPicker with my own design..
Like other widget switch, user gets value true or false, here I want to get value of selected month and year from this custom widget..
user don't need to code for taponPlus and tapOnMinus buttons...
design is shown in image
here is my code
class _HomeScreenState extends State<HomeScreen> {
int current_month = DateTime.now().month;
int current_year = DateTime.now().year;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(children: [
Container(
height: 100,
child: Material(
color: Colors.grey,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
onPressed: () {
setState(() {
if (current_month == 1) {
current_year--;
current_month = 12;
} else
current_month--;
});
},
icon: Icon(Icons.arrow_back)),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
current_year.toString(),
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
DateFormat('MMMM')
.format(DateTime(0, current_month))
.toString(),
style: TextStyle(
fontSize: 30,
color: Colors.black,
fontWeight: FontWeight.bold),
),
],
),
IconButton(
onPressed: () {
setState(() {
if (current_month == 12) {
current_year++;
current_month = 1;
} else
current_month++;
});
},
icon: Icon(Icons.arrow_forward)),
],
),
),
),
Expanded(
child: Container(
color: Colors.blue,
child: Center(child: Text('Output')),
),
),
]),
),
);
}
}

Text overflow flutter

I have the next widget, which is rendered with overflow. I have tried to solve, but i don't know. Can anyone help me? The aim is to do a custom card inside listview.
I have tried to wrap with expanded buth then, the error is referenced with constraints.
import 'package:flutter/material.dart';
import '../../shared/AppTheme.dart';
class ComandaScreen extends StatefulWidget {
const ComandaScreen({Key? key}) : super(key: key);
#override
State<ComandaScreen> createState() => _ComandaScreenState();
}
class _ComandaScreenState extends State<ComandaScreen> {
bool expanded = false;
int unidades = 0;
final List<Map<String, dynamic>> _items = List.generate(
10, (index) => {'id': index, 'Nombre': 'Nuggets $index',
'isExpanded': false, "unidades": 8});
#override
Widget build(BuildContext context) {
final ButtonStyle flatButtonStyle = TextButton.styleFrom(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
);
return Scaffold(
appBar: AppBar(
title: const Text('Comanda'),
backgroundColor: AppTheme.backgroundColor,
foregroundColor: AppTheme.primaryTextColor,
elevation: 0,
),
body: SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
// expandedHeaderPadding: const EdgeInsets.all(10),
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: const Duration(milliseconds: 200),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
// backgroundColor: item['isExpanded'] == true ? Colors.cyan[100] : Colors.white,
headerBuilder: (context, isExpanded) {
return Container(
margin: const EdgeInsets.all(10),
child: Row(children: [
const CircleAvatar(
child: Text(
'1',
textAlign: TextAlign.center,
)),
const SizedBox(
width: 10,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Nuggets',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w600),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: const [
Text(
'Unidades: ${7}',
style: TextStyle(color: Colors.black),
),
Text(
'Pendientes: 400',
style: TextStyle(color: Colors.black),
),
],
),
const SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
'Precio: 10 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
Text(
'Total: 70 €',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black),
),
],
),
],
),
],
),
),
]),
);
},
body: ButtonBar(
alignment: MainAxisAlignment.spaceAround,
buttonHeight: 52.0,
buttonMinWidth: 90.0,
children: <Widget>[
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] += 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.add,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Más'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {
setState(() {
item['unidades'] -= 1;
});
},
child: Column(
children: const <Widget>[
Icon(
Icons.remove,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Menos'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.edit_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Editar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.delete_outline_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Eliminar'),
],
),
),
TextButton(
style: flatButtonStyle,
onPressed: () {},
child: Column(
children: const <Widget>[
Icon(
Icons.card_giftcard_outlined,
color: AppTheme.grismedio,
),
// Padding(
// padding: EdgeInsets.symmetric(vertical: 2.0),
// ),
// Text('Invitar'),
],
),
)
],
),
isExpanded: item['isExpanded'],
),
)
.toList(),
// Card_lineaComanda(flatButtonStyle),
),
),
);
}
}
I 've edited the code to show all screen widget.
Image of result of code before:
For desktop applications, you can prevent the resize with breakpoint, so the error won't happen. In the pubsec.yaml file, add the following dependency.
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
And in your main method before runapp add this code with min-width and min-height below which the app won't resize.
const double desktopMinWidth = 800.0;
const double desktopMinHeight = 600.0;
if (Platform.isMacOS || Platform.isWindows) {
setWindowMinSize(const Size(desktopMinWidth, desktopMinHeight));
setWindowMaxSize(Size.infinite);
}
Note: Once done restart your app.
For mobile, it is entirely a different case. You might need to restructure the design

how to manage textField controller for multiple dataRow in dataTable Flutter

In my flutter project, I want to make the screen which is user enter quantity for multiple product. I want to manage text controllers for multiple data rows in the data table.
My data table code is:
TextEditingController textController = TextEditingController();
AlertDialog(
content: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.height,
margin: EdgeInsets.all(0),
child: ListView(
padding: EdgeInsets.all(0),
primary: true,
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: [
DataTable(
columns: [
DataColumn(
label: Text(
"Product",
softWrap: true,
),
),
DataColumn(
label: Text(
"Qty",
),
),
DataColumn(
label: Text(
"Rs",
)),
DataColumn(
label: SizedBox(
width: 40,
child: Text(
'BalQty',
),
),
),
DataColumn(
label: SizedBox(
width: 40,
child: Text(
'Stock',
),
),
),
],
rows: listOfProduct!
.map(
((element) => DataRow(
cells: <DataCell>[
DataCell(Text(
element.name,
)),
DataCell(
TextField(
controller: textEditingController,
maxLength: 4,
decoration: InputDecoration(
labelText: 'Qty',
labelStyle: TextStyle(fontSize: 9.sp),
counterText: "",
),
),
),
DataCell(
Text(
(element.pTR ?? 0).toStringAsFixed(2),
),
),
DataCell(Text(
element.text!.printDashIfEmpty(),
)),
DataCell(Text(
(element.balQty ?? 0).toStringAsFixed(2),
)),
],
)),
)
.toList(),
),
],
),
),
actions: <Widget>[
OutlinedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Cancel",
)),
SizedBox(
width: 10,
),
OutlinedButton(
onPressed: () async {
print("QUANTITY : $textEditingController");
listSearchProductMaster!.forEach((e) {
return print("TEXT CONTROLLER: ${e.textEditingController}");
});
},
child: Text(
"Add",
))
],
)
The output I see is that the quantity that the user inserts should be added to the particular product.
Currently, my application output is
Does anyone help?
Well, in my case, my approach was:
When user tap item to edit, show modal with initial value
User make input and tab Confirm button
after valid input, apply
It wrap focus node and controller, so easy to use.
But it force user to dig in 1 more UI level, so maybe there are better ways, but it works anyway.
I made TextEditModal widget and function to show that.
Future<String> showSingleTextEditDialog({
#required BuildContext context,
String initText = '',
}) async {
String text = initText;
bool submit = false;
await showDialog(
context: context,
builder: (_) {
return _SingleTextEditDialog(
text: text,
textChanged: (value) => text = value,
onSubmit: () => submit = true,
);
},
);
return submit ? text : null;
}
class _SingleTextEditDialog extends StatefulWidget {
_SingleTextEditDialog({
Key key,
#required this.text,
#required this.textChanged,
this.onSubmit,
}) : super(key: key);
final String text;
final ValueChanged<String> textChanged;
final VoidCallback onSubmit;
#override
_SingleTextEditDialogState createState() => _SingleTextEditDialogState();
}
class _SingleTextEditDialogState extends State<_SingleTextEditDialog> {
TextEditingController textController;
#override
void initState() {
super.initState();
textController = TextEditingController(text: widget.text);
}
#override
void dispose() {
textController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return SimpleDialog(
children: [
DecoInput(
controller: textController,
onChanged: widget.textChanged,
),
VSpace.md,
StyledInterfaceButton(
onTap: () {
setState(() => widget.onSubmit());
Navigator.of(context).pop();
},
text: 'Confirm',
),
// VSpace.md,
],
);
}
}
and use like
onTap: () async {
HapticFeedback.mediumImpact();
final input = await showSingleTextEditDialog(
context: context,
initText: text,
);
if (input == null) return;
// valid user input here
valueChanged(input); // apply user input
},
This is not complete code. I minimized code for readability. So ignore if there are any error.
Add your table code inside SingleChildScrollView() with scrollDirection: Axis.horizontal refer below code hope it help to you
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Column(
children: <Widget>[
Container(
margin: EdgeInsets.all(20),
child: Table(
defaultColumnWidth: FixedColumnWidth(80.0),
border: TableBorder.all(
color: Colors.black,
style: BorderStyle.solid,
width: 2),
children: [
TableRow(
children: [
Column(
children: [
Text(
'Website',
style: TextStyle(fontSize: 20.0),
),
],
),
Column(
children: [
Text(
'Tutorial',
style: TextStyle(fontSize: 20.0),
),
],
),
Column(
children: [
Text(
'Review',
style: TextStyle(fontSize: 20.0),
),
],
),
Column(children: [
Text(
'Review',
style: TextStyle(fontSize: 20.0),
),
]),
Column(
children: [
Text(
'Review',
style: TextStyle(fontSize: 20.0),
),
],
),
],
),
TableRow(children: [
Column(
children: [
Text('Javatpoint'),
],
),
Column(
children: [
Text('Flutter'),
],
),
Column(
children: [
Text('5*'),
],
),
Column(
children: [
Text('5*'),
],
),
Column(
children: [
Text('5*'),
],
),
]),
TableRow(
children: [
Column(children: [
Text('Javatpoint'),
]),
Column(
children: [
Text('MySQL'),
],
),
Column(
children: [
Text('5*'),
],
),
Column(children: [
Text('5*'),
]),
Column(children: [
Text('5*'),
]),
],
),
],
),
),
],
),
),
Scroll your table horizontaly
Your screen like - >

How to add/sum TextFormField values in Flutter?

How can I add the values of several formfields in Flutter to dynamically calculate a total field? Imagine E.g. If the three textformfields had values of 1, 2, 3 then the total field should display 6.
I am able to convert the values to double using double.parse(value).
Code:
class _GivingPageState extends State<GivingPage> {
final _formKey = GlobalKey<FormState>();
double collection1;
double collection2;
double collection3;
double total;
#override
void initState() {
collection1 = 0;
collection2 = 0;
collection3 = 0;
total = 0;
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Column(
children: <Widget>[
Expanded(
child: buildContent(),
),
],
),
),
),
);
}
Widget buildContent() {
return Container(
color: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: lightCard(
child: Container(
padding: EdgeInsets.only(left: 0.0, right: 10, top: 10, bottom: 10),
child: Padding(
padding: const EdgeInsets.only(left: 18.0, bottom: 10),
child: Container(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 0.0, bottom: 10),
child: Text(
'Collection Baskets',
style: TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
),
Text('Which collection baskets(s) are you giving to?'),
SizedBox(height: 15),
_buildBasket(
collectionName: 'Amount 1',
collection: collection1,
),
SizedBox(height: 10),
_buildBasket(
collectionName: 'Amount 2',
collection: collection2,
),
SizedBox(height: 10),
_buildBasket(
collectionName: 'Amount 3',
collection: collection3,
),
SizedBox(height: 10),
_buildTotal()
],
),
),
),
),
)),
));
}
void _updateTotal() {
setState(() {
total = collection1 + collection2 + collection3;
});
}
Row _buildBasket(
{#required String collectionName, #required double collection}) {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(
collectionName,
style: TextStyle(fontSize: 16),
),
),
SizedBox(width: 10),
Expanded(
flex: 1,
child: Row(
children: <Widget>[
Text(
'£',
style: TextStyle(fontSize: 20),
),
SizedBox(width: 10),
Expanded(
child: numberFormField(
onChanged: (value) {
setState(() {
collection = double.parse(value);
_updateTotal();
});
},
textFieldKey: null),
),
],
),
),
],
);
}
Row _buildTotal() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(
'Total',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
SizedBox(width: 10),
Expanded(
flex: 1,
child: Row(
children: <Widget>[
Text(
'£',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(width: 10),
Expanded(
child: Container(
height: 50,
decoration: BoxDecoration(
color: AppColors.secondaryElement,
borderRadius: Radii.k25pxRadius,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"${formatNumber(amount: total)}",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
),
],
),
),
),
],
),
),
],
);
}
}
Does this work for you?
class Home extends StatefulWidget{
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home>{
double firstFieldValue = 0;
double secondFieldValue = 0;
double thirdFieldValue = 0;
#override
Widget build(BuildContext context){
return Scaffold(
body: Center(
child: Column(
children: [
TextField(
onChanged: (value){
if(value.isEmpty){
setState(() => firstFieldValue = 0);
}else{
setState((){
firstFieldValue = double.parse(value);
});
}
}
),
TextField(
onChanged: (value){
if(value.isEmpty){
setState(() => secondFieldValue = 0);
}else{
setState((){
secondFieldValue = double.parse(value);
});
}
}
),
TextField(
onChanged: (value){
if(value.isEmpty){
setState(() => thirdFieldValue = 0);
}else{
setState((){
thirdFieldValue = double.parse(value);
});
}
}
),
Text(
"${firstFieldValue + secondFieldValue + thirdFieldValue}"
)
]
)
),
);
}
}

How to Get the Number of Pages in Pageview to be used in a line indicator in Flutter?

May i ask for help on how to get the number of pages inside a pageview,
similar to listview you can get the number of list via listview.length, but for pageview there is no pageview.length property that i can use,
i tried using pageview.builder but i couldnt initiate the data as a list showig an issue that i need to initiate it as an initializers?,
please help me figure it out
i need the data inside the pageview to be used inside the _lineprogressindicator, to show how many are the questionaires inside to make an indicator
here is my code
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:survey/content/thankyou.dart';
import 'package:survey/widgets/animations.dart';
import 'package:survey/widgets/buttonstyle.dart';
import 'package:survey/widgets/widgetlist.dart';
class questionaires extends StatefulWidget {
#override
_questionairesState createState() => _questionairesState();
}
class _questionairesState extends State<questionaires> {
TextStyle conqueststyle = TextStyle(
fontSize: 15, fontWeight: FontWeight.bold, color: Colors.indigo);
TextStyle questionstyle = TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
);
String titletop = 'Post Visit Patient Satisfaction';
String q1 = "Sample Question HERE";
String q2 = "Sample Question HERE";
String q3 = "Sample Question HERE";
String q4 = "Sample Question HERE";
int percentagenum = 0;
int _currValue = 1;
bool _loading;
double _progress;
final _texteditingcontroller = TextEditingController();
final _pageController = PageController(initialPage: 0, keepPage: true);
var _currentpage = 0;
List answernumbers = ["5", "4", "3", "2", "1"];
List currentselectedvalue = [];
List usingCollection1 = [
"Excellent",
"Very Good",
"Good",
"Fair",
"Poor",
];
#override
void dispose() {
super.dispose();
_texteditingcontroller.dispose();
_loading = false;
_progress = 0.0;
percentagenum = 0;
_currValue = 0;
usingTimes1 = '';
usingTimes = '';
usingTimes2 = '';
}
void initState() {
super.initState();
usingTimes1 = '';
usingTimes = '';
usingTimes2 = '';
_loading = false;
_progress = 0.0;
percentagenum = 0;
_texteditingcontroller.clear();
_currValue = 0;
}
void pageChanged(int index) {
setState(() {
_currentpage = index;
});
}
void _selectedanswers(data1, data2) {
if (_progress.toStringAsFixed(1) == '1.0') {
print(data1);
print(data2);
_texteditingcontroller.text;
}
}
void _updateProgress() {
setState(() {
_progress += 0.25;
percentagenum += 25;
if (_progress.toStringAsFixed(1) == '1.0') {
_loading = false;
_progress = 0;
percentagenum = 0;
Navigator.push(context, FadeRoute(page: thankyou()));
return;
}
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomPadding: false,
body: Padding(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 100,
height: 60,
child: Image.asset(imgtit),
),
Stack(
children: <Widget>[
Container(
child: Text(
titletop,
style: conqueststyle,
maxLines: 1,
),
),
_buildPageView(),
_lineprogressindicator()
],
)
],
),
),
),
);
}
_buildPageView() {
return Container(
height: MediaQuery.of(context).size.height / 1.25,
child: PageView(
controller: _pageController,
onPageChanged: (index) {
pageChanged(index);
},
children: <Widget>[
_emojiquestions(q1),
_selectedutton(q2),
_numberrating(q3),
_textboxquestion(q4),
],
));
}
_lineprogressindicator() {
return Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: Column(
children: <Widget>[
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(50.0),
),
color: Colors.indigo,
onPressed: () {
_pageController.nextPage(
duration: kTabScrollDuration, curve: Curves.ease);
_loading = !_loading;
_updateProgress();
},
child: Icon(
Icons.check,
color: Colors.white,
size: 50,
),
),
SizedBox(
height: 10,
),
Text('%$percentagenum'),
LinearProgressIndicator(
value: _progress,
),
],
),
);
}
_emojiquestions(String quest1) {
final using = usingCollection1[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 1',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest1),
maxLines: 5,
style: conqueststyle,
),
Expanded(
child: Center(
child: Container(
height: 300,
child: ListView.separated(
separatorBuilder: (context, index) => SizedBox(height: 10),
itemCount: usingCollection1.length,
itemBuilder: (context, index) => GestureDetector(
onTapUp: (index) {
_selectedanswers(index, null);
},
child: Card(
color: usingTimes == usingCollection1[index]
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
height: 50,
width: 70,
child: Image.asset(emojiimage[index]),
),
Text(usingCollection1[index])
],
),
Divider(
height: index < usingCollection1.length ? 1.0 : 0.0,
),
],
),
),
),
)),
),
)
],
);
}
_selectedutton(String quest1) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 1',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest1),
maxLines: 5,
style: conqueststyle,
),
Expanded(
child: Center(
child: Container(
height: 300,
child: Column(
children: List.generate(usingCollection1.length, (int index) {
final using = usingCollection1[index];
return GestureDetector(
onTap: () {
setState(() {
_currValue = index;
_selectedanswers(index, null);
usingTimes = using.identifier;
});
},
child: Card(
color: usingTimes == using.identifier
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Radio(
value: index,
groupValue: _currValue,
onChanged: (val) =>
setState(() => _currValue = val),
),
Text(using.displayContent)
],
),
Divider(
height:
index < usingCollection1.length ? 1.0 : 0.0,
),
],
),
));
}),
),
),
),
)
],
);
}
_numberrating(quest) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 2',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest),
maxLines: 5,
style: conqueststyle,
),
Text("**5 is the highest"),
Container(
height: MediaQuery.of(context).size.height / 12.0,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: usingCollection1.length,
itemBuilder: (context, index) {
final using = usingCollection1[index];
return GestureDetector(
onTapUp: (index) {
setState(() {
_selectedanswers(null, index);
usingTimes = using.identifier;
});
},
child: Card(
color: usingTimes == using.identifier
? Colors.blue.withAlpha(100)
: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
side: BorderSide(color: Colors.indigoAccent)),
child: Column(
children: <Widget>[
SizedBox(
height: 50,
width: 50,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
answernumbers[index],
textAlign: TextAlign.center,
style: conqueststyle,
),
],
)),
),
],
),
),
);
},
),
)
],
);
}
_textboxquestion(quest) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Question 2',
style: conqueststyle,
textAlign: TextAlign.right,
),
SizedBox(
height: 20,
),
TextField(
decoration: InputDecoration.collapsed(hintText: quest),
maxLines: 5,
style: conqueststyle,
),
TextFormField(
decoration: InputDecoration(
hintText: "Your FeedBack Here",
border: OutlineInputBorder(),
),
controller: _texteditingcontroller,
maxLines: 7,
style: conqueststyle,
)
],
);
}
}
For your case were the number of elements is known beforehand, I would suggest that you store your pages in a local variable and then call length on it. A small snippet would look something like this:
class MyState extends State<MyWidget> {
List<Widget> _pages = [
Container(color: Colors.blue,),
Container(color: Colors.amber,),
];
#override
Widget build(BuildContext context) {
return MyComplexWidgetTree(
child: PageView(
controller: PageController(),
children: _pages,
),
);
}
void _myMethodThatRequiresNumberOfPages() {
int numberOfPages = pages.length;
}
}