在我的 onChanged 方法中,我向串列中添加了一個條目并更改了復選框的狀態。如何將 onChanged 移動到單獨的方法中?
BlocConsumer<StudentBloc, StudentState>(
listener: _checkboxListener,
builder: (context, state) {
return Expanded(
child: ListView.builder(
itemCount: _lessonsList.length,
itemBuilder: (BuildContext context, int index) {
final lesson = _lessonsList[index];
bool? checkboxValue = _checkboxValues[index];
return CheckboxListTile(
title: Text(lesson.lessonName ?? ''),
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
value: checkboxValue,
onChanged: (bool? value) {
_checkedLesson.add(lesson);
setState(
() {
_checkboxValues[index] = value ?? false;
},
);
},
);
},
),
);
},
),
uj5u.com熱心網友回復:
你可以這樣做:
BlocConsumer<StudentBloc, StudentState>(
listener: _checkboxListener,
builder: (context, state) {
return Expanded(
child: ListView.builder(
itemCount: _lessonsList.length,
itemBuilder: (BuildContext context, int index) {
final lesson = _lessonsList[index];
bool? checkboxValue = _checkboxValues[index];
return CheckboxListTile(
title: Text(lesson.lessonName ?? ''),
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
value: checkboxValue,
onChanged: myFunction,
);
},
),
);
},
),
void myFunction(bool? value) {
_checkedLesson.add(lesson);
setState(
() {
_checkboxValues[index] = value ?? false;
},
);
}
在 Android Studio 中執行此操作的最快方法是將游標放在您(bool? value)現在所在的位置,然后按 Ctrl Alt M。這是提取方法的快捷方式。
如果你想將其他引數傳遞給這個函式,你可以這樣做:
BlocConsumer<StudentBloc, StudentState>(
listener: _checkboxListener,
builder: (context, state) {
return Expanded(
child: ListView.builder(
itemCount: _lessonsList.length,
itemBuilder: (BuildContext context, int index) {
final lesson = _lessonsList[index];
bool? checkboxValue = _checkboxValues[index];
return CheckboxListTile(
title: Text(lesson.lessonName ?? ''),
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
value: checkboxValue,
onChanged: (bool? value) => myFunction(value, index, lesson),
);
},
),
);
},
),
void myFunction(bool? value, int index, Lesson lesson) { //I don't know what type lesson is, I just assumed Lesson here
_checkedLesson.add(lesson);
setState(
() {
_checkboxValues[index] = value ?? false;
},
);
}
uj5u.com熱心網友回復:
該onChanged引數采用具有可為空的布爾引數的函式,即void Function(bool?)
所以你必須創建一個這樣的函式:
void aFunctionToPassIn(bool? value){
// Do something in here
}
然后傳給onChangedlikeonChanged: aFunctionToPassIn,
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487752.html
