skip to Main Content

I am using a local HTML string, in which I use the style.css from assets/html directory:

  final String html = """    <!DOCTYPE html>  
    <html>  
    <head>  
        <link rel="stylesheet" type="text/css" href="assets/html/style.css">  
        </head>  
      <body>  
       <h2>Simple HTML with External CSS</h2>  
        <p class="blue">This is a blue color paragraph</p>  
        <p class="red">This is a red color paragraph</p>  
        <p class="green">This is a green color paragraph</p>  
      </body>  
    </html>  """;

The css file is:

body{
background-color:lavender;
text-align: center;
}
h2{
font-style: italic;
size: 30px;
color: #f08080;
}
p{
font-size: 20px;
}

.blue{
color: blue;
}
.red{
color: red;
}
.green{
color: green;
}

The code of the WebViewPlus is:

return Scaffold(
    backgroundColor: Colors.blue,
    body: WebViewPlus(
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (controller) {
        controller.loadString(html);
      },
    )
  );

The result is just a simple text without using the style.css file. How should I reference the css file from assets folder?
What should I use for href="<LOCATION_OF_CSS>"

I modified pubspec.yaml to include the assets/html folder.

Thanks!

2

Answers


  1. To reference a CSS file from the assets folder in your Flutter WebView, you need to use a data: URL scheme. Here’s how you can modify your code to load the CSS file correctly:

    First, make sure the style.css file is included in the pubspec.yaml file under the assets section:

      flutter:
      assets:
        - assets/html/style.css
    

    Next, update your HTML string to reference the CSS file using the data: URL scheme:

        final String html = """
      <!DOCTYPE html>
      <html>
        <head>
          <link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8;base64,${base64Encode(File('assets/html/style.css').readAsBytesSync())}">
        </head>
        <body>
          <h2>Simple HTML with External CSS</h2>
          <p class="blue">This is a blue color paragraph</p>
          <p class="red">This is a red color paragraph</p>
          <p class="green">This is a green color paragraph</p>
        </body>
      </html>
    """;
    

    In the above code, the File(‘assets/html/style.css’).readAsBytesSync() loads the CSS file from the assets folder and base64Encode encodes it to a base64 string.

    Now, when you load the HTML string in the WebView using controller.loadString(html), the CSS file will be correctly referenced and applied to the HTML content.

    Note: Ensure that the CSS file is located at assets/html/style.css relative to the pubspec.yaml file.

    With these modifications, the WebView should render the HTML content with the styles defined in the CSS file.

    Login or Signup to reply.
  2. To use the CSS content in your HTML, you can replace the tag with a tag and include the CSS content directly within the HTML string.

    Here’s an example of how you can modify the HTML string to include the CSS content:

    return Scaffold(
      backgroundColor: Colors.blue,
      body: FutureBuilder<String>(
        future: rootBundle.loadString('assets/html/style.css'),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.hasData) {
            final cssContent = snapshot.data;
            final modifiedHtml = html.replaceAll(
              '<link rel="stylesheet" type="text/css" href="assets/html/style.css">',
              '<style type="text/css">$cssContent</style>',
            );
    
            return WebView(
              initialUrl: Uri.dataFromString(modifiedHtml, mimeType: 'text/html', encoding: Encoding.getByName('utf-8')).toString(),
              javascriptMode: JavascriptMode.unrestricted,
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text('Error loading CSS file'),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
    

    In this modified code, the tag is replaced with a tag, and the CSS content (cssContent) is included within the tag using string interpolation (‘$cssContent’).

    Now, when the WebView loads the modified HTML, it will apply the CSS styles directly within the HTML document.

    Note: Make sure the CSS file (style.css) contains valid CSS syntax to avoid any issues with rendering.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search