If a user has entered any URL while typing the description in the textfield and I want that url to be detected and want a preview of that URL displayed as well.
Does anyone have some ideas on how that can be achieved?
CodePudding user response:
You can listen to the TextEditingController
to detect it when it's printed, in my example, I will recognize the URL that contains "http" text :
in StatefulWidget
:
late TextEditingController _controller;
@override
void initState() {
_controller = TextEditingController();
_controller.addListener(() {
if (_controller.text.contains("http")) {
print("link detected :");
print(_controller.text.split(' ').firstWhere(
(element) => element.startsWith("http"),
));
}
});
super.initState();
}
The TextField
widget:
TextField(
controller: _controller, // assign that controller
);
after a hot restart, when your type in the TextField
, if some text starts with the "http" ( which is the URL) the listener will print it.
you can use it to achieve your goal.
CodePudding user response:
you can use anylink package :
on TextField(
onChange: (url){
bool isValidUrl = AnyLinkPreview.isValidLink(
url,
protocols: ['http', 'https'],
hostWhitelist: ['https://youtube.com/'],
hostBlacklist: ['https://facebook.com/'],
);
if(isValidUrl){
setState((){
_currentUrl = url;
})
}
}
)
AnyLinkPreview(
...
link: _currentUrl,
..