Reputation: 36
I have a widget that can highlight text by tap, so I put 13 same widgets on one page. what I want to do is only one widget can highlight in some time.
Column(
children: List.generate(13, (index) {
return MySelectableText(
data: data,
highLight: highLight[index],
callBack: () {
print('fjkdsfj');
setState(() {
for (int i = 0; i < 13; i++) {
highLight[i] = false;
}
highLight[index] = true;
});
},
);
}),
)
SelectableText.rich(TextSpan(
children: List.generate(
widget.data.length,
(index) => TextSpan(
text: widget.data[index] + ' ',
style: TextStyle(
backgroundColor: selectIndex == index && widget.highLight
? Colors.blueAccent
: Colors.transparent),
recognizer: TapGestureRecognizer()
..onTap = () {
print(index.toString() + widget.highLight.toString());
setState(() {
selectIndex = index;
widget.callBack();
});
}))));
this can work, but what I want is that I do not need to maintain and set a highLight list because actually the widget num is dynamically changed.
Upvotes: 0
Views: 421
Reputation: 669
Please refer to this example to understand the logic and modify it according to your need.
import 'package:flutter/material.dart';
class DesignPage extends StatefulWidget {
const DesignPage({Key? key}) : super(key: key);
@override
_DesignPageState createState() => _DesignPageState();
}
class _DesignPageState extends State<DesignPage> {
int selectedItems = -1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:const Text("Patient List",style: TextStyle(color: Colors.black,fontSize: 16),),backgroundColor: Colors.white,
leading: const Icon(Icons.menu,color: Colors.grey,),
actions: [
Padding(
padding: const EdgeInsets.only(right: 20),
child: ClipRRect(child: Image.network("https://www.whatsappprofiledpimages.com/wp-content/uploads/2021/08/Profile-Photo-Wallpaper.jpg",width: 30,height: 30,fit: BoxFit.cover,),
borderRadius: BorderRadius.all(Radius.circular(50)),),
),
],
),
body: Column(
children: List.generate(13, (index) {
return clickableItem(index);
}),
),
);
}
Widget clickableItem(int index){
return GestureDetector(
onTap: (){
setState(() {
selectedItems = index;
});
},
child: Text("Text $index",style: TextStyle(backgroundColor:
selectedItems == index ? Colors.green : Colors.white
),),
);
}
}
Upvotes: 0