skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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,
    ..
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search