Home > Mobile >  Dart is replacing "&" with "\u0026" in a URL
Dart is replacing "&" with "\u0026" in a URL

Time:10-25

I am using flutter to process a link and download it to the device using dio package.

But the problem is dart is replacing all '&' with '\u0026' and making the link unusable. is there a way to avoid this problem? Thanks in advance.

Here's the code:

      const uuid = Uuid();
      final Dio dio = Dio();

      // * create random id for naming downloaded file
      final String randid = uuid.v4();

      // * create a local instance of state all media
      List<MediaModel> allMedia = state.allMedia;

      // * create an instance of IGDownloader utility class from ~/lib/utilities
      final IGDownloader igd = IGDownloader();

      // * make a download link from provided link from the GetNewMedia event
      final link = await igd.getPost(event.link);
      link.replaceAll('\u0026', '&');
      print(await link);

Output:

// expected : "http://www.example.com/example&examples/"
// result: "http://www.example.com/example\u0026example"

CodePudding user response:

replaceAll returns the modified string, but leaves original String untouched. Try:

print(link.replaceAll('\u0026', '&'));

or

newLink = link.replaceAll('\u0026', '&');
print(newLink);

CodePudding user response:

Pass your url to cleanContent function and don't forget to add imports

import 'package:html/parser.dart';
import 'package:html_unescape/html_unescape.dart';

static String cleanContent(String content, {bool decodeComponent = false}) {
    if (content.contains("<p>")) {
      content = content.replaceAll("<p>", "").trim();
    }
    if (content.contains("</p>")) {
      content = content.replaceAll("</p>", "").trim();
    }
    var unescape = HtmlUnescape();
    content = unescape.convert(content).toString();
    if (content.contains("\\<.*?\\>")) {
      content = content.replaceAll("\\<.*?\\>", "").trim();
    }
    content = parseHtmlString(content,decodeComponent: decodeComponent);
    return content;
  }

  static String parseHtmlString(String htmlString,{bool decodeComponent = false}) {
    final document = parse(htmlString);
    String parsedString = parse(document.body!.text).documentElement!.text;
    if(parsedString.contains(":")){
      parsedString = parsedString.replaceAll(":", ":");
    }
    if(parsedString.contains("/")){
      parsedString = parsedString.replaceAll("/", "/");
    }
    if(decodeComponent){
      parsedString = Uri.decodeComponent(parsedString);
    }

    return parsedString;
  }
  • Related