Flutter - RangeError(index) - android

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

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.

Incorrect use of ParentDataWidget | Flutter | DropDown Button

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(),

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,),
],
),
),
)
],
),
),

only static members can be accessed in initializers in stepper widget

This is a flutter app using the stepper widget to display other widgets. I need to put two checkbox tile widgets in a row and which will be seperated by columns. I have initialized the checkbox tile widget but it keeps displaying a 'only static members can be accessed in initializers' for the onChanged and value parameters
class MyHome extends StatefulWidget {
#override
MyHomeState createState() => new MyHomeState();
}
class MyHomeState extends State<MyHome> {
void onChanged(bool value){
setState(() {
_isChecked = value;
});
}
static bool _isChecked = false;
// init the step to 0th position
int current_step = 0;
List<Step> my_steps = [
new Step(
// Title of the Step
title: new Text("Residential Data"),
// Content, it can be any widget here. Using basic Text for this example
content: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Activity"),
),
Row(
children: <Widget>[
Column(
children: <Widget>[
CheckboxListTile(value: _isChecked, onChanged: (bool value){setState(() {
_isChecked = value;
});})
],
),
Column(
children: <Widget>[
CheckboxListTile(value: _isChecked, onChanged: (bool value){onChanged(value);},)
],
)
],
),
Row(
children: <Widget>[
Column(
children: <Widget>[
CheckboxListTile(value: _isChecked, onChanged: (bool value){onChanged(value);})
],
),
Column(
children: <Widget>[
CheckboxListTile(value: _isChecked, onChanged: (bool value){onChanged(value);},)
],
)
],
)
],
),//new Text("Hello!"),
isActive: true),
new Step(
title: new Text("Step 2"),
content: new Text("World!"),
// You can change the style of the step icon i.e number, editing, etc.
state: StepState.editing,
isActive: true),
new Step(
title: new Text("Step 3"),
content: new Text("Hello World!"),
isActive: true),
];
#override
Widget build(BuildContext context) {
return new Scaffold(
// Appbar
appBar: new AppBar(
// Title
title: new Text("Simple Material App"),
),
// Body
body: new Container(
child: new Stepper(
// Using a variable here for handling the currentStep
currentStep: this.current_step,
// List the steps you would like to have
steps: my_steps,
// Define the type of Stepper style
// StepperType.horizontal : Horizontal Style
// StepperType.vertical : Vertical Style
type: StepperType.vertical,
// Know the step that is tapped
onStepTapped: (step) {
// On hitting step itself, change the state and jump to that step
setState(() {
// update the variable handling the current step value
// jump to the tapped step
current_step = step;
});
// Log function call
print("onStepTapped : " + step.toString());
},
onStepCancel: () {
// On hitting cancel button, change the state
setState(() {
// update the variable handling the current step value
// going back one step i.e subtracting 1, until its 0
if (current_step > 0) {
current_step = current_step - 1;
} else {
current_step = 0;
}
});
// Log function call
print("onStepCancel : " + current_step.toString());
},
// On hitting continue button, change the state
onStepContinue: () {
setState(() {
// update the variable handling the current step value
// going back one step i.e adding 1, until its the length of the step
if (current_step < my_steps.length - 1) {
current_step = current_step + 1;
} else {
current_step = 0;
}
});
// Log function call
print("onStepContinue : " + current_step.toString());
},
)),
);
}
}
You created your widget tree as a field of the class:
class Foo extends StatelessWidget {
String parameter;
Widget widget = Text(parameter); // only static members can be accessed in initializers
}
You shouldn't do this. You cannot initialize a field of an object with other class properties. Instead, create that widget inside the build method:
class Foo extends StatelessWidget {
String parameter;
#override
Widget build(BuildContext context) {
Widget widget = Text(parameter);
// TODO: do something width `widget`
}
}

Categories

Resources