Incorrect use of ParentDataWidget | Flutter | DropDown Button - android

I got an error Incorrect use of parentdata widget when trying to add a DropdownButton within a row Widget.
Here I've added two elements, Text Widget and DropdownButton within a Row Widget
Row(
children: <Widget>[
Expanded(flex: 1, child: Text(' Source :')),
Expanded(
flex: 4,
child: FutureBuilder<SourceData>(
future: sourceData,
builder: (context, snapshot) {
return sourceDropDownList(snapshot.data.sources);
return CircularProgressIndicator();
})
) // FutureBuilder
],
), // Row
Here's the DropDownList Function returning a DropdownButton
Widget sourceDropDownList(List<Sources> sources) {
var sourceNameList = List<String>();
for (var i = 0; i < sources.length; i++) {
sourceNameList.add(sources[i].name);
}
return DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: sourceNameList.map((value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
);
}
Here is the screenshot of exact error message :
[Error Message][1]
[Actual Representation of widget][2]
[1]: https://i.stack.imgur.com/w9QsX.png
[2]: https://i.stack.imgur.com/ALAOT.png

You should define your list type.
items: sourceNameList.map((String value) {
return new DropdownMenuItem(
value: value,
child: new Text(
value.name,
)
);
}).toList(),

Related

hi why my list item turn null in the futurebuilder of flutter?

Hi in my flutter app have FutureBuilder that return listview, my list listview create some button for update the hive table. when I click the first time on one of buttons everything is run smoothly, but when I click on same button again my hive key turn to null and program show my this error: "type 'Null' is not a subtype of type 'int' "
I write print all over my code but still I do not get it why the key turn null from the second time.
How can I Correct this? please help my.
my Futurebuilder body is:
FutureBuilder<List>(
future: controller.showTaskList(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return SizedBox(
height: Get.height,
child: const Center(
child: CircularProgressIndicator(),
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return ListView.separated(
scrollDirection: Axis.vertical,
physics:
const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: data.length,
itemBuilder: (context, index) {
// controller.taskIconCheckList
// .clear();
for (int i = 0;
i < data.length;
i++) {
if (data[i].status == true) {
controller.taskIconCheckList
.add(true.obs);
} else {
controller.taskIconCheckList
.add(false.obs);
}
}
return ListTile(
leading: Obx(
() => PageTransitionSwitcher(
transitionBuilder: (
child,
primaryAnimation,
secondaryAnimation,
) {
return SharedAxisTransition(
animation:
primaryAnimation,
secondaryAnimation:
secondaryAnimation,
transitionType:
SharedAxisTransitionType
.horizontal,
fillColor:
Colors.transparent,
child: child,
);
},
duration: const Duration(
milliseconds: 800),
child: controller
.taskIconCheckList[
index]
.value
? SizedBox(
child: IconButton(
icon: const Icon(
Icons
.check_circle_rounded,
color: Colors
.lightGreenAccent,
),
onPressed: () {
controller
.functionTaskIconCheckList(
index,
);
print('طول دیتا');
print(data.length.toString());
print('مقدار ایندکس');
print(index.toString());
print('مقدار کلید');
print(data[index].key.toString());
print(data[index].taskText.toString());
controller
.updateStatusTask(
index,
data[index]
.key); // here when i first click // return key currectly, but after that show null and updatestatusetask not run and show error.
},
),
)
: IconButton(
onPressed: () {
controller
.functionTaskIconCheckList(
index,
);
print('طول دیتا');
print(data.length.toString());
print('مقدار ایندکس');
print(index.toString());
print('مقدار کلید');
print(data[index].key.toString());
print(data[index].taskText.toString());
controller
.updateStatusTask(
index,
data[index]
.key); // here when i first click // return key currectly, but after that show null and updatestatusetask not run and show error.
},
icon: const Icon(
Icons
.radio_button_unchecked_outlined,
color: Colors.red,
),
),
),
),
title: Text(data[index].taskText,
style: normalTextForCategory),
subtitle: Text(
data[index]
.date
.toString()
.substring(0, 10),
textDirection:
TextDirection.ltr,
textAlign: TextAlign.right,
style: normalTextForSubtitle,
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
onPressed: () {
myDefaultDialog(
'هشدار',
'آیا از حذف این گزینه اطمینان دارید؟',
'بله',
'خیر',
() {
Get.back();
mySnakeBar(
'',
'گزینه مورد نظر با موفقیت حذف شد.',
Icons
.warning_amber_rounded,
Colors.yellow);
},
);
},
icon: const Icon(
Icons.delete),
color: Colors.redAccent,
),
IconButton(
onPressed: () {
Get.offNamed(
Routs.editTaskScreen,
arguments: 'edit');
},
icon: const Icon(
Icons.edit_calendar,
color:
Colors.yellowAccent,
),
),
],
),
);
},
separatorBuilder:
(BuildContext context,
int index) {
return const Divider(
height: 2,
color: Colors.white70,
);
},
);
}
}
},
),
this is my functionTaskIconCheckList form controller:
functionTaskIconCheckList(int index) {
taskIconCheckList[index].value = !taskIconCheckList[index].value;}
and this the updatestatusetask function
updateStatusTask(int index,int taskKey) async {
print('در تابع آپدیت ایندکس هست: ${index.toString()}');
print('در تابع آپدیت کی هست: ${taskKey.toString()}');
var taskBox = await Hive.openBox('task');
var filterTask = taskBox.values.where((task) => task.key == taskKey).toList();
Task task = Task(
filterTask[0].taskText,
filterTask[0].date,
taskIconCheckList[index].value,
filterTask[0].deleteStatus,
null,
null,
filterTask[0].taskCatId,
filterTask[0].userId);
await taskBox.put(taskKey, task);}
and this is my showtasklist function:
Future<List> showTaskList() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskBox = await Hive.openBox('task');
var filterTask = taskBox.values
.where((task) => task.userId == sharedPreferences.getInt('key'))
.toList();
return filterTask;}
this is my model:
#HiveType(typeId: 2)
class Task extends HiveObject{
#HiveField(0)
String taskText;
#HiveField(1)
DateTime date;
#HiveField(2)
bool status;
#HiveField(3)
bool deleteStatus;
#HiveField(4)
int taskCatId;
#HiveField(5)
int userId;
#HiveField(6)
User? user;
#HiveField(7)
TaskCat? taskCat;
Task(this.taskText, this.date, this.status, this.deleteStatus, this.user,
this.taskCat, this.taskCatId, this.userId);
}
One possible solution would be to wait for the Future function to finish and then load the list. If it tries to load the list early before finishing up the Future function, it might presume the value to be null.
Hope this helps.
Still I do not know what is cause this problem, But I found an alternative temporary solution. I create temporary Int list. then just before the return listTile in the futureBuilder body, I write the Loop and save all of the key in that list. finally instead of pass the "data[index].key." I pass my key from that temporary Int list. so everything work fine now
this is my part of code change from before, but still I want know main solution.
return ListView.separated(
scrollDirection: Axis.vertical,
physics:
const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: data.length,
itemBuilder: (context, index) {
// controller.taskIconCheckList
// .clear();
for (int i = 0;
i < data.length;
i++) {
Get.find<
HomeScreenController>()
.taskKey.add(data[i].key);
if (data[i].status == true) {
Get.find<
HomeScreenController>()
.taskIconCheckList
.add(true.obs);
} else {
Get.find<
HomeScreenController>()
.taskIconCheckList
.add(false.obs);
}
}
return ListTile(

How to assign value to variable from future before screen built?

In my application user can have multiple home and multiple rooms for each home. On top of my application I have dropdown box which im trying to set default value to selectedHome by user. Below that dropdown box I am showing the rooms in the home selected by user. In firebase I have rooms collection under each home. I'm getting the selected home data from firebase too. Also to show the rooms in selected home i need to query by home name. I have two FutureBuilder as you can see code below. One of them to get the selectedHome data from firebase and other for the getting the rooms in that home from firebase. As I said before to get the rooms in selected home I need to query by name of the home so I have a parameter which is the value of dropdownbox. In my code the problem is getting the rooms part is working before I get the selectedHome data from firebase and assign it to dropdown value. In this case I'm getting "Null check operator used on a null value".
Basicly the question is how can i assign value from future to variable before screen gets build.
Here you can see the code for getting selected home data from firebase;
Future<String> selectedHome() async {
return await database.selectedHome();
}
Future<String> selectedHome() async {
DocumentSnapshot docS =
await firestore.collection("users").doc(auth.currentUser()).get();
String selectedHome = (docS.data() as Map)["selectedHome"];
return selectedHome;
}
Here you can see the code for getting room data based on selectedHome from firebase;
Future<List<Map>> deviceAndRoomInfo() async {
return database.numberOfRooms(_dropdownValue!);
}
Future<List<Map>> numberOfRooms(String selectedHome) async {
List<Map> prodsList = [];
final snapshot = await firestore
.collection("users")
.doc(auth.currentUser())
.collection("homes")
.doc(selectedHome)
.collection("rooms")
.get();
List listOfRooms = snapshot.docs;
for (int a = 1; a <= listOfRooms.length; a++) {
var productsInRoom = await firestore
.collection("users")
.doc(auth.currentUser())
.collection("homes")
.doc(selectedHome)
.collection("rooms")
.doc(listOfRooms[a - 1]["roomName"])
.collection("products")
.get();
List prodList = productsInRoom.docs
.map((e) => DeviceModel.fromMap(e.data()))
.toList();
Map qq = {
"roomName": listOfRooms[a - 1]["roomName"],
"deviceInfo": prodList
};
prodsList.add(qq);
}
return prodsList;
}
Here you can see the code for screen contains 2 future builder that i told;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shelly_ess_production/constants.dart';
import 'package:shelly_ess_production/helper_widgets/loading_widget.dart';
import 'package:shelly_ess_production/screens/home_screen/components/circle_room_data.dart';
import 'package:shelly_ess_production/screens/home_screen/components/device_in_room_card.dart';
import 'package:shelly_ess_production/screens/home_screen/provider/home_screen_provider.dart';
import 'package:shelly_ess_production/screens/models/device_model.dart';
import 'package:shelly_ess_production/size_config.dart';
class Body extends StatefulWidget {
const Body({Key? key}) : super(key: key);
#override
State<Body> createState() => _BodyState();
}
class _BodyState extends State<Body> {
#override
Widget build(BuildContext context) {
var providerHelper =
Provider.of<HomeScreenProvider>(context, listen: false);
return SafeArea(
child: Padding(
padding:
EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(0.07)),
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: getProportionateScreenHeight(0.02),
),
Consumer<HomeScreenProvider>(builder: (context, data, child) {
return FutureBuilder<List<String>>(
future: data.getHomesAndSelected(),
builder: (context, snapshot) {
if (snapshot.hasData) {
data.setDropDownValue = snapshot.data![0];
return DropdownButtonHideUnderline(
child: DropdownButton(
iconEnabledColor: kPrimaryColor,
iconDisabledColor: kPrimaryColor,
style: TextStyle(
color: kPrimaryColor,
fontSize: getProportionateScreenHeight(0.05)),
menuMaxHeight: getProportionateScreenHeight(0.4),
borderRadius: BorderRadius.circular(15),
key: UniqueKey(),
value: data.dropdownValue,
isExpanded: true,
icon: const Icon(Icons.arrow_downward),
onChanged: (String? newValue) async {
data.setDropDownValue = newValue;
await data.changeSelectedHome();
},
items: snapshot.data!
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
alignment: Alignment.center,
value: value,
child: Text(value),
);
}).toList(),
),
);
} else {
return Transform.scale(
scale: 0.5,
child: const Center(
child: CircularProgressIndicator(),
),
);
}
});
}),
SizedBox(
height: getProportionateScreenHeight(0.02),
),
SizedBox(
height: getProportionateScreenHeight(0.14),
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (context, index) {
return CircleRoomData(
title: "Oda Sayısı",
icon: Icons.meeting_room,
content: "8",
);
}),
),
Consumer<HomeScreenProvider>(builder: (context, data, snapshot) {
return FutureBuilder<List<Map>>(
future: data.deviceAndRoomInfo(data.dropdownValue!),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
physics: const NeverScrollableScrollPhysics(),
itemCount: snapshot.data!.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return Column(
children: [
Divider(
thickness:
getProportionateScreenHeight(0.002),
),
Text(
snapshot.data![index]["roomName"],
style: TextStyle(
fontWeight: FontWeight.bold,
color: kSecondaryColor,
fontSize:
getProportionateScreenHeight(0.03)),
),
SizedBox(
height: getProportionateScreenHeight(0.01),
),
Text(
"${(snapshot.data![index]["deviceInfo"] as List).length.toString()} Cihaz",
style:
const TextStyle(color: kSecondaryColor),
),
SizedBox(
height: getProportionateScreenHeight(0.02),
),
GridView.builder(
shrinkWrap: true,
physics:
const NeverScrollableScrollPhysics(),
itemCount: (snapshot.data![index]
["deviceInfo"] as List)
.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
itemBuilder: (context, indexx) {
print(index);
return DeviceInRoom(
icon: Icons.light,
productName: ((snapshot.data![index]
["deviceInfo"]
as List)[indexx] as DeviceModel)
.deviceName,
);
})
],
);
});
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
});
}
)
],
)),
),
);
}
}
Am not certain where your error is coming from, but from what I see it maybe as a result of one of your functions returning null and a rendering of your content happens before the data is received.
You could try one of these:
You could declare the return type of your feature as being nullable for example you are expecting a value of type int:
Future<int?> xyz(){
......
return .....;
}
Now because your return type is nullable you wont have an issues as long as the receiving variable is also nullable.
Alternatively:
Future<int?> xyz(){
......
return ..... ?? 10 /*some default value*/;
}
because you know you result could be null you could also provide an optional default value incase your Future call returns a null value.

How to make dependent multilevel DropDown in flutter?

I am trying to make dependent multilevel dropdown first contains states list and second contains cities list, all the data fetched from API. Initially, I load state dropdown, when I select the state then cities of that state load if I select city, the city selected successfully but when I change the state value then an error occurs. What is the right way to reload the second dropdown if changes will make in the first dropdown?
Error: There should be exactly one item with [DropdownButton]'s value: Instance of 'City'.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
Future _state;
Future _city;
#override
void initState() {
super.initState();
_state = _fetchStates();
}
Future<List<StateModel>> _fetchStates() async {
final String stateApi = "https://dummyurl/state.php";
var response = await http.get(stateApi);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<StateModel> listOfUsers = items.map<StateModel>((json) {
return StateModel.fromJson(json);
}).toList();
return listOfUsers;
} else {
throw Exception('Failed to load internet');
}
}
Future<List<City>> _fetchCities(String id) async {
final String cityApi = "https://dummyurl/city.php?stateid=$id";
var response = await http.get(cityApi);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
print(items);
List<City> listOfUsers = items.map<City>((json) {
return City.fromJson(json);
}).toList();
return listOfUsers;
} else {
throw Exception('Failed to load internet');
}
}
State Dropdown
FutureBuilder<List<StateModel>>(
future: _state,
builder: (BuildContext context,
AsyncSnapshot<List<StateModel>> snapshot) {
if (!snapshot.hasData)
return CupertinoActivityIndicator(animating: true,);
return DropdownButtonFormField<StateModel>(
isDense: true,
decoration: spinnerDecoration('Select your State'),
items: snapshot.data
.map((countyState) => DropdownMenuItem<StateModel>(
child: Text(countyState.billstate),
value: countyState,
))
.toList(),
onChanged:(StateModel selectedState) {
setState(() {
stateModel = selectedState;
_city = _fetchCities(stateModel.billstateid);
});
},
value: stateModel,
);
}),
City Dropdown
FutureBuilder<List<City>>(
future: _city,
builder: (BuildContext context,
AsyncSnapshot<List<City>> snapshot) {
if (!snapshot.hasData)
return CupertinoActivityIndicator(animating: true,);
return DropdownButtonFormField<City>(
isDense: true,
decoration: spinnerDecoration('Select your City'),
items: snapshot.data
.map((countyState) => DropdownMenuItem<City>(
child: Text(countyState.billcity)
.toList(),
onChanged: (City selectedValue) {
setState(() {
cityModel = selectedValue;
});
},
value: cityModel,
);
}),
class StateModel {
String billstateid;
String billstate;
String billcountryid;
StateModel({this.billstateid, this.billstate, this.billcountryid});
StateModel.fromJson(Map<String, dynamic> json) {
billstateid = json['billstateid'];
billstate = json['billstate'];
billcountryid = json['billcountryid'];
}
}
class City {
String billcityid;
String billcity;
String billstateid;
City({this.billcityid, this.billcity, this.billstateid});
City.fromJson(Map<String, dynamic> json) {
billcityid = json['billcityid'];
billcity = json['billcity'];
billstateid = json['billstateid'];
}
You have to make cityModel = null in onChanged callback of State dropdown.
setState(() {
cityModel = null;
stateModel = selectedState;
_city = _fetchCities(stateModel.billstateid);
});
There should be exactly one item with [DropdownButton]'s value:
Instance of 'City'. Either zero or 2 or more [DropdownMenuItem]s were
detected with the same value
This error occurs here, because the value you are passing not in the items of DropdownButtonFormField(city dropdown).
When you select a State, you are fetching new list of city list and passing it to CityDropDown but forgot to clear the previously selected city(cityModel).
You can also refer this example: DartPad
I am also facing a problem until new state data is not fetched It is showing previous state data. The approach I have used is different. I am not using future Builders.
Here is My code:
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new Container(
width: 450,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Source",
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
source1 != null ? DropdownButtonFormField<String>(
isExpanded: true,
validator: (value) => value == null ? 'field required' : null,
hint: Text("Select Source"),
items: source1.data.map((item) {
// print("Item : $item");
return DropdownMenuItem<String>(
value: item.descr,
child: Text(item.descr),
);
}).toList(),
onChanged: (String cat) {
setState(() {
subsourseStr = null;
sourceStr = cat;
getSubSource2(sourceStr);
});
},
value: sourceStr,
):SizedBox(height: 10),
],
),
),
)
],
),
),
//
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new Container(
width: 450,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Sub Source",
style: TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
subSource2 != null ? DropdownButtonFormField<String>(
isExpanded: true,
validator: (value) => value == null ? 'field required' : null,
hint: Text("Select Sub Source"),
items: subSource2.data.map((item) {
return DropdownMenuItem<String>(
value: item.descr,
child: Text(item.descr),
);
}).toList(),
onChanged: (String cat) {
setState(() {
subsourseStr = cat;
});
},
value: subsourseStr,
):SizedBox(height: 10,),
],
),
),
)
],
),
),

How to generate list of items from checkbox selection in flutter?

I am trying to create a list of ids & names from checkbox selection and i want to pass that array list in navigator.pop but somehow i am not able to do it.?
I tried to create model and put that as in list object which can give me my selected values in list or array but I am getting it with last extra (comma(,))
My checkbox and code to create list and pass it into navigator.pop.
THIS IS MAIN PAGE WHERE I WANT TO GET AND REDIRECT TO SECOND LIST PAGE.
var tempRoomFace;
getRoomFaceData() async {
tempRoomFace = await Navigator.push(
context, MaterialPageRoute(builder: (context) => RoomFacilities()));
for (int i = 0; i < areaDataResult.length; i++) {
_selectedroom = _selectedroom + tempRoomFace[i].name + ", ";
_selectedroomID = _selectedroomID + tempRoomFace[i].id + ", ";
print("selected rooms : $_selectedroomID");
}
}
THIS IS LIST PAGE... TO CREATE LIST
------------------ code for passing value ---------------------
List<RoomFacilityModel.Message> tempRoomData =
List<RoomFacilityModel.Message>();
//
List<RoomFacilityModel.Message> roomListOBJ =
List<RoomFacilityModel.Message>();
onPressed: () {
Navigator.pop(context, tempRoomData);
for (int i = 0; i < tempRoomData.length; i++) {
print(
"City List : ${tempRoomData[i].fcid} + ${tempRoomData[i].name} ");
}
},
------------------- Code for checkbox ------------------
Container(
child: CheckboxListTile(
title: Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
color: Colors.black,
),
height: 26,
width: 26,
child: Image.network(
roomListOBJ[index].icon,
),
),
SizedBox(width: 10),
Text(roomListOBJ[index].name),
],
),
value: roomListOBJ[index].isCheck,
onChanged: (bool value) async {
//
setState(() {
roomListOBJ[index].isCheck = value;
if (value) {
tempRoomData.add(RoomFacilityModel.Message(
fcid: roomListOBJ[index].fcid,
name: roomListOBJ[index].name));
} else {
tempRoomData.removeAt(index);
}
});
}),
);
I want to get resulat on my main page as
tempRoomFace = [TV, Safe box, curtains, iron]
tempRoomFaceID = [3,4,8,1]
You could modify this as much as you want.
class MultiCheckBoxField extends StatelessWidget {
const MultiCheckBoxField({
Key key,
this.count = 1,
this.onSaved,
}) : super(key: key);
final int count;
final FormFieldSetter<List<bool>> onSaved;
#override
Widget build(BuildContext context) {
return FormField<List<bool>>(
initialValue: List.filled(count, false),
onSaved: onSaved,
builder: (FormFieldState field) {
return Column(
mainAxisSize: MainAxisSize.min,
children: List.generate(
count,
(int index) {
return Checkbox(
onChanged: (bool value) {
field.value[index] = value;
field.didChange(field.value);
},
value: field.value[index],
);
},
),
);
},
);
}
}

Flutter - RangeError(index)

I get an error while I'm building a ListView. In this flutter app I try to count for each column some points when a button is clicked. But I'm getting always the same error.
══╡ EXCEPTION CAUGHT BY GESTURE
I/flutter (28729): The following RangeError was thrown while handling
a gesture: I/flutter (28729): RangeError (index): Invalid value: Valid
value range is empty: 0
This is my code and I hope somebody is able to help me fixing the error:
import 'package:flutter/material.dart';
class Punktezaehler extends StatefulWidget{
final List<String> spieler_namen;
Punktezaehler(this.spieler_namen);
#override
State<StatefulWidget> createState() => new _Punktezaehler(this.spieler_namen);
}
class _Punktezaehler extends State<Punktezaehler>{
final List<String> spieler_namen;
_Punktezaehler(this.spieler_namen);
List<int> punkteanzahl_teamEins = [];
List<int> punkteanzahl_teamZwei = [];
int team1_hinzugezaehlt = 0;
int team2_hinzugezaehlt = 0;
#override
Widget build(BuildContext context) {
var spieler1 = spieler_namen[0].substring(0,3);
var spieler2 = spieler_namen[1].substring(0,3);
var spieler3 = spieler_namen[2].substring(0,3);
var spieler4 = spieler_namen[3].substring(0,3);
return new Scaffold(
appBar: new AppBar(
automaticallyImplyLeading: false,
title: new Text("$spieler1 & $spieler2 vs" +" $spieler3 & $spieler4"),
actions: <Widget>[
],
),
body: Container(
child: new Row(
children: <Widget>[
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(1, 2)
)
],
),
new Padding(padding: EdgeInsets.only(left: 100.0)),
new Expanded(
child: ListView.builder(
itemCount: punkteanzahl_teamEins.length, //--> Error is thrown here
itemBuilder: (context, index){
return Text(punkteanzahl_teamEins[index].toString());
}
),
),
new Expanded(
child: ListView.builder(
itemCount: punkteanzahl_teamZwei.length, //--> Error is thrown here
itemBuilder: (context, index){
return Text(punkteanzahl_teamZwei[index].toString());
}
),
),
new Column(
children: <Widget>[
new IconButton(
icon: Icon(Icons.exposure_plus_2),
onPressed: () => punkte_hinzuzaehlen(2, 2)
)],
)
],
)
),
);
}
void punkte_hinzuzaehlen(int team, int nummer){
if (team == 1){
setState(() {
punkteanzahl_teamEins[team1_hinzugezaehlt] = nummer;
team1_hinzugezaehlt++;
});
}
else if(team == 2){
setState(() {
punkteanzahl_teamZwei[team2_hinzugezaehlt] = nummer;
team2_hinzugezaehlt++;
});
}
}
}
the problem that when you click a button you are calling this line
punkteanzahl_teamEins[team1_hinzugezaehlt]
and team1_hinzugezaehlt have an initial value of 0 but every time the user click the button this value will increase by one
so let's say your punkteanzahl_teamEins list contains 2 items in the fourth click the value team1_hinzugezaehlt will be 4 witch will cause this error . so the solution is to check whether the value is in the range or not
if (team1_hinzugezaehlt<punkteanzahl_teamEins.length){
setState(() {
punkteanzahl_teamEins[team1_hinzugezaehlt] = nummer;
team1_hinzugezaehlt++;
});
}
and do the same for the second function

Categories

Resources