问题
I would like to know if there's any way(implementation, package) I could use to make a specific part of a dynamically received String, CLICKABLE.
For example, let's take a look at this json file.
I would like to know if after I display this user in a list builder which contains all the users, can I have some kind of a clickable flatbutton on that highlighted "client-server" word, so that when I press it, I can navigate let's say to a separate dictionary page, and search for that word furthermore?
I mean, how can I mark the "client-server" word, so Flutter can help me get it dynamically clickable while building the list? Is there any way I could do that? Especially being able to have an index or an id attached to it so that I can use it in another screen?
As a solution, I was wondering if I could wrap that "client-server" word in the json file with some button tags like in html ( client-server ) and when I set the string to the flutter widget it could somehow recognise it with an id or a name so that when I press it, I can pass the name or/and the id to the Navigator searching for it in the dictionary, but frankly as I've searched on the web, there's nothing that can do this type of behaviour.
Thank you in advance for taking the time to read my question.
回答1:
List<Map> products = [];
@override
void initState() {
super.initState();
Map tmp = {
"products": [
{
"prod_id": "prod-345",
"name": "Something",
"category": "Cloth",
"thumbnail": "",
"desc": 'An example of description',
"click_on": 'example',
'action': 'https://google.com'
},
{
"prod_id": "prod-123",
"name": "Something Else",
"category": "Watch",
"thumbnail": "",
"desc": '2nd example of description',
"click_on": 'description',
'action': 'second_screen'
},
]
};
products.addAll(tmp['products']);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Let\'s parse some JSON'),
),
body: Container(
padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
child: ListView.builder(
itemCount: products.length,
itemBuilder: (cc, ind) {
return ListTile(
title: Text(products[ind]['name']),
subtitle: Text.rich(TextSpan(
text: products[ind]['desc'].toString().substring(
0,
products[ind]['desc'].toString().indexOf(
products[ind]['click_on'].toString())),
children: <TextSpan>[
TextSpan(
//if you want style !
style:TextStyle(
decoration:TextDecoration.underline,
),
text: products[ind]['click_on'],
recognizer: new TapGestureRecognizer()
..onTap = () => print('Tap Here onTap'),
),
TextSpan(
text: products[ind]['desc'].toString().substring(
products[ind]['desc'].toString().indexOf(
products[ind]['click_on']
.toString()) +
products[ind]['click_on']
.toString()
.length,
products[ind]['desc'].toString().length),
)
])));
})));
}
来源:https://stackoverflow.com/questions/59619419/how-to-make-a-piece-of-text-dynamically-received-from-json-clickable-in-flutter