首页 > 解决方案 > 如何使用flutter webview获取html元数据

问题描述

我需要使用 flutter_webview 从 html 头获取元数据。在这种情况下,我需要从中获得价值

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">

所以我可以在我的应用程序上使用网站主题颜色。

我怎样才能做到这一点?

标签: webviewflutter

解决方案


如果您想从网页获取元数据标签,那么您可以使用“alice: ^0.0.4”库。

首先在 pubspec.yaml 的 "alice: ^0.0.4" 中声明

下面是我为您创建的完整示例,您可以在其中看到我打印了正文、bodyBytes、标题以及 contentLength,我们可以从中获取所有“”标签:

import 'package:flutter/material.dart';
import 'package:alice/alice.dart';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:dio/dio.dart';

Alice alice = Alice(showNotification: true);

void main() {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Alice alice;
  Dio dio;
  HttpClient httpClient;

  @override
  void initState() {
    alice = Alice(showNotification: true);
    dio = Dio();
    dio.interceptors.add(alice.getDioInterceptor());
    httpClient = HttpClient();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: alice.getNavigatorKey(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Alice HTTP Inspector example'),
        ),
        body: Center(
            child:
            Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              RaisedButton(
                child: Text("Run HTTP Requests"),
                onPressed: _runHttpRequests,
              ),
              RaisedButton(
                child: Text("Run HTTP Insepctor"),
                onPressed: _runHttpInspector,
              ),
            ])),
      ),
    );
  }

  void _runHttpRequests() async {
    Map<String, dynamic> body = {"title": "foo", "body": "bar", "userId": "1"};
    http
        .post('https://www.google.com', body: body)
        .then((response) {
      alice.onHttpResponse(response, body: body);

      print(response.body);
      print(response.bodyBytes);
      print(response.headers);
      print(response.contentLength);

    });

    dio.post("https://www.google.com", data: body);

  }

  void _runHttpInspector() {
    alice.showInspector();
  }
}

推荐阅读