Home > database >  Flutter, How to Replace Html tags to Text?
Flutter, How to Replace Html tags to Text?

Time:09-06

When I am fetching data from the internet I get for example <p> Shawarma </p>, How can I display the data without appearing the <p> tag? Note that there is a package called: html_character_entities and others but how can I use them in the builder?

           FutureBuilder<Iterable<SubCategories>>(
                builder: (context, snapshot) {
                    return ListView.builder(
                      itemBuilder: (context, index) =>
                          Text(
                            snapshot.data!.elementAt(index).description,
                          ),
                    );
                }),

CodePudding user response:

You can use this package : https://pub.dev/packages/flutter_html it will render hrml tags. OR you can use this function by creating self :

static String stripHtml(String text) {
  return text.replaceAll(RegExp(r'<[^>]*>|&[^;] ;'), ' ');
}

In you code you can use like this by using that fucntion:

FutureBuilder<Iterable<SubCategories>>(
            builder: (context, snapshot) {
                return ListView.builder(
                  itemBuilder: (context, index) =>
                      Text(
                        stripHtml (snapshot.data!.elementAt(index).description,),
                      ),
                );
            })
 

CodePudding user response:

No need for a package for this ...

  FutureBuilder<Iterable<SubCategories>>(
                builder: (context, snapshot) {
                    return ListView.builder(
                      itemBuilder: (context, index) =>
                          Text(
                            snapshot.data!.elementAt(index).description.replaceAll(RegExp(r'<[^>]*>|&[^;] ;'), ''),
                          ),
                    );
                }),

CodePudding user response:

You can use html package like this:

String _removeHtmlTag(String str) {
    String result = '';
    final document = parse(str);
    if (document.body != null) {
      result = parse(document.body!.text).documentElement!.text;
    }
    return result;
  }

and use this like this:

print("result = ${_removeHtmlTag('<p> Shawarma </p>')}"); //result = Shawarma
  • Related