Flutter加载自定义CSS样式文件方法

1. 使用 flutter_html 包(推荐)

如果你需要在 Flutter 中显示 HTML 并应用 CSS 样式,可以使用 flutter_html 包:

Dart 复制代码
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter/services.dart' show rootBundle;

class HtmlWithCssPage extends StatefulWidget {
  @override
  _HtmlWithCssPageState createState() => _HtmlWithCssPageState();
}

class _HtmlWithCssPageState extends State<HtmlWithCssPage> {
  String htmlContent = '';
  String cssContent = '';

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

  Future<void> _loadResources() async {
    // 加载 HTML 文件
    htmlContent = await rootBundle.loadString('assets/sample.html');
    
    // 加载 CSS 文件
    cssContent = await rootBundle.loadString('assets/styles.css');
    
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('HTML with CSS')),
      body: SingleChildScrollView(
        child: Html(
          data: '''
            <style>$cssContent</style>
            $htmlContent
          ''',
          // 自定义样式处理
          style: {
            "body": Style(
              fontSize: FontSize(16.0),
              color: Colors.black,
            ),
            "h1": Style(
              color: Colors.blue,
              fontWeight: FontWeight.bold,
            ),
          },
        ),
      ),
    );
  }
}

pubspec.yaml 中配置:

Dart 复制代码
flutter:
  assets:
    - assets/sample.html
    - assets/styles.css

2. 对于 Web 平台的特殊处理

直接添加 CSS 到 Web 页面

web/index.html 中添加 CSS 链接:

Dart 复制代码
<!DOCTYPE html>
<html>
<head>
  <!-- 其他 meta 标签 -->
  <link href="styles/custom.css" rel="stylesheet">
</head>
<body>
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

动态注入 CSS

Dart 复制代码
import 'dart:html' as html;

void injectCustomCss() {
  final styleElement = html.StyleElement();
  styleElement.id = 'custom-styles';
  styleElement.text = '''
    .custom-class {
      color: red;
      font-size: 20px;
    }
  ''';
  html.document.head!.append(styleElement);
}

3. 使用 webview_flutter 显示带样式的 HTML

Dart 复制代码
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewWithCss extends StatefulWidget {
  @override
  _WebViewWithCssState createState() => _WebViewWithCssState();
}

class _WebViewWithCssState extends State<WebViewWithCss> {
  late WebViewController _controller;

  Future<void> _loadHtmlWithCss() async {
    final htmlContent = await rootBundle.loadString('assets/content.html');
    final cssContent = await rootBundle.loadString('assets/styles.css');
    
    final fullHtml = '''
      <!DOCTYPE html>
      <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>$cssContent</style>
      </head>
      <body>
        $htmlContent
      </body>
      </html>
    ''';
    
    _controller.loadHtmlString(fullHtml);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('WebView with CSS')),
      body: WebView(
        initialUrl: 'about:blank',
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (controller) {
          _controller = controller;
          _loadHtmlWithCss();
        },
      ),
    );
  }
}

4. 创建 assets 文件夹和文件

Dart 复制代码
lib/
assets/
├── styles.css
└── sample.html

styles.css 示例:

css 复制代码
body {
  font-family: Arial, sans-serif;
  line-height: 1.6;
  color: #333;
}

h1 {
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
}

.highlight {
  background-color: #fffacd;
  padding: 10px;
  border-radius: 5px;
}

pubspec.yaml 配置:

Dart 复制代码
flutter:
  assets:
    - assets/styles.css
    - assets/sample.html

注意事项

  1. 性能考虑:大量使用 HTML/CSS 可能会影响性能

  2. 平台限制:CSS 样式主要在 Web 平台有效,移动端可能需要替代方案

  3. 样式冲突:Flutter 样式和 CSS 样式可能会冲突

  4. 安全性:动态加载 HTML/CSS 时注意 XSS 攻击防护

替代方案

如果不需要真正的 HTML/CSS,考虑使用 Flutter 的原生样式系统:

Dart 复制代码
// 在 ThemeData 中定义全局样式
MaterialApp(
  theme: ThemeData(
    textTheme: TextTheme(
      headline1: TextStyle(
        fontSize: 24,
        fontWeight: FontWeight.bold,
        color: Colors.blue,
      ),
      bodyText1: TextStyle(
        fontSize: 16,
        color: Colors.black87,
      ),
    ),
  ),
);

// 使用 TextStyle
Text(
  'Styled Text',
  style: TextStyle(
    fontSize: 20,
    color: Colors.red,
    fontWeight: FontWeight.bold,
  ),
);

使用哪种方式我们要根据具体需求具体分析。

相关推荐
嚣张丶小麦兜2 小时前
认识vite
前端·javascript·vue.js
音浪豆豆_Rachel2 小时前
Flutter跨平台通信的智能配置:Pigeon注解配置与鸿蒙生态深度集成
flutter·华为·harmonyos
Bryce李小白2 小时前
深入理解WidgetsFlutterBinding
flutter
玲小珑2 小时前
请求 ID 跟踪模式:解决异步请求竞态条件
前端
lcc1872 小时前
CSS 定位
css
开心_开心急了2 小时前
AI+PySide6实现自定义窗口标题栏目(titleBar)
前端
开心_开心急了3 小时前
Ai加Flutter实现自定义标题栏(appBar)
前端·flutter
布列瑟农的星空3 小时前
SSE与流式传输(Streamable HTTP)
前端·后端
GISer_Jing3 小时前
跨境营销前端AI应用业务领域
前端·人工智能·aigc
oak隔壁找我3 小时前
Node.js的package.json
前端·javascript