嗨,我想更新列表内的文本颜色视图生成器仅为选定的项目。我们怎么能做到??
我只想更新选定的文本颜色,前一项的颜色将为黑色。
这是我的代码:
我的第一个小部件是statefulWidget
Expanded(
flex: 6,
child: ListView.builder(
itemCount: languageValue.length,
shrinkWrap: true,
scrollDirection: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (ctx, index) {
LanguageCode lang = languageValue[index];
return _LanguageItemSelection(
languageName: lang.value,
isSelected: index,
onLanguageSelect: () {
setState(() {
_langValue = lang.value!;
});
debugPrint('Language Value => ${lang.code}');
},
);
},
),
),
My Second langueselecteditem:
class _LanguageItemSelection extends StatelessWidget {
_LanguageItemSelection({
Key? key,
this.languageName,
this.onLanguageSelect,
this.isSelected,
}) : super(key: key);
String? languageName;
VoidCallback? onLanguageSelect;
int? isSelected;
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
debugPrint('index => ${isSelected}');
return Column(
children: [
const SizedBox(
height: 5,
),
InkWell(
onTap: onLanguageSelect,
child: Text(
languageName!,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
color: isSelected == _selectedIndex ? Colors.blue : Colors.black,
),
),
),
const SizedBox(
height: 5,
),
const Divider(
color: Colors.grey,
thickness: 0.8,
),
],
);
}
}
我已经从afgprogrammer找到了解决方案
我在statefulwidget和它的工作中创建了一个函数
_LanguageItemSelection(String name, int index) {
return InkWell(
onTap: () {
setState(() {
selectedLanguage = index;
_langValue = name;
});
},
child: Column(
children: [
const SizedBox(
height: 5,
),
Text(
name,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
color: selectedLanguage == index ? Colors.blue : Colors.black,
),
),
const SizedBox(
height: 5,
),
const Divider(
color: Colors.grey,
thickness: 0.8,
),
],
),
);
}
}