Home > database >  Make links clickable in Flutter if rendered via Wordpress JSON API
Make links clickable in Flutter if rendered via Wordpress JSON API

Time:08-18

Is there a way we can make the links in Flutter clickable if they are being fetched via JSON API? I mean, I can see that my links get a different color, but when I try to click on it, nothing happens. Trying it on an emulator, have not released the app yet.

JSON:

"content": {
  "rendered": "<p>Absolutely great movie <a href="test">Test</a>!</p>\n"},

I need to make sure that "Test" is clickable and sends me to the post in my app.

This is the content JSON file:

class Content {
  String? raw;
  String? rendered;
  bool? protected;
  int? blockVersion;

  Content({this.rendered});

  Content.fromJson(Map<String, dynamic> json) {
    raw = json['raw'];
    rendered = json['rendered'];
    protected = json['protected'];
    blockVersion = json['block_version'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    
    data['raw'] = this.raw;
    data['rendered'] = this.rendered;
    data['protected'] = this.protected;
    data['block_version'] = this.blockVersion;
    
    return data;
  }
}

How can I make them clickable automatically?

  @override
  void initState() {
    super.initState();

    _content = widget.post.content?.rendered ?? "";
    _content = _content.replaceAll('localhost', '192.168.6.165');
  }

The text itself:

Html(
            data: _content // this is where all texts are,
            // blockSpacing: 0.0,
          ),

If I use RichText, it gives me the following error:

error: The argument type 'String' can't be assigned to the parameter type 'InlineSpan'. (argument_type_not_assignable)

CodePudding user response:

RichText(
      text: TextSpan(
        text: 'Hello ',
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(
              text: 'world!',
              style: TextStyle(fontWeight: FontWeight.bold)),
          TextSpan(
              text: ' click here!',
              recognizer: TapGestureRecognizer()
                ..onTap = () => print('click')),
        ],
      ),
    );

CodePudding user response:

Okay, I partially solved it.

Still, the problem I have with this is that it opens a browser - I need it to go to the posts itself on my app, but I can't get this to work. Just sharing anyway.

    Html(
    data: _content,
    onLinkTap: (url, _, __, ___) async {
      if (await launch(url!)) {
        await launch(
          url,
        );
      }
    },
  ),
  • Related