如何在flutter中打印Web平台的响应?

问题描述 投票:0回答:1

在我的代码中,我已经在网络平台上启动了URL,也得到了响应,但我无法从网络端获取并打印响应。

这是我的简单代码:

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart' as html;

class MyWebApp extends StatefulWidget {
  const MyWebApp({super.key});

  @override
  State<MyWebApp> createState() => _MyWebAppState();
}

class _MyWebAppState extends State<MyWebApp> {
  final url =
      "https://accounts.google.com/o/saml2/initsso?idpid=C02qtgmcd&spid=859837136968&forceauthn=false";
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Web Application"),
      ),
      body: Container(
        color: Colors.blue,
        child: Center(
          child: ElevatedButton(
              onPressed:
                  () {
                html.window.open(url, 'Google Authentication', 'popup');
              },
              child: const Text("Login")),
        ),
      ),
    );
  }
}

这是我在网络端得到的回复,但无法得到它:

{"status":1,"msg":"user Authenticated !!","user":{"userFirstName":"Max","userLastName":"Well","userEmail":"[email protected]","userType":"manager","manager":true,"employee":false,"teamLead":false},"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImdhdXJhdkB0aGVsYXR0aWNlLmluIiwiZmlyc3ROYW1lIjoiR2F1cmF2IiwibGFzdE5hbWUiOiJLdW1hciIsIm1hbmFnZXIiOnRydWUsImVtcGxveWVlIjpmYWxzZSwidGVhbUxlYWQiOmZhbHNlLCJpYXQiOjE3MDAyMDQ4NjQsImV4cCI6MTcwMDI5MTI2NH0.alsdjflaksjweio39lskdjf923030923jslkdf"}

任何人都可以帮我在控制台中获取并打印响应吗?

flutter dart url
1个回答
0
投票

尝试使用监听器监听从打开的窗口发送的消息,使用

html.window.onMessage.listen
。收到消息后,会将其解析为 JSON 并打印到控制台。然后,您可以根据需要在 Flutter 应用程序中操作或使用接收到的数据。

请记住,这假设打开的窗口发送一条带有响应 JSON 的消息。您可能需要根据从打开的 URL 发送响应的方式来调整此代码。

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:universal_html/html.dart' as html;

class MyWebApp extends StatefulWidget {
  const MyWebApp({Key? key}) : super(key: key);

  @override
  State<MyWebApp> createState() => _MyWebAppState();
}

class _MyWebAppState extends State<MyWebApp> {
  final url = "your url";
      

  void _openUrl() {
    html.window.open(url, 'Google Authentication', 'popup');
    html.window.onMessage.listen((event) {
      final receivedData = json.decode(event.data);
      print(receivedData); // Print the received data in the console
      // Handle the received data as needed
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Web Application"),
      ),
      body: Container(
        color: Colors.blue,
        child: Center(
          child: ElevatedButton(
            onPressed: _openUrl,
            child: const Text("Login"),
          ),
        ),
      ),
    );
  }
}

替代解决方案,

要从打开的 URL 捕获响应数据,您可以在打开的窗口中使用 JavaScript 中的

Window.postMessage
并在 Flutter 应用程序中侦听此消息。

首先你应该制作一个像下面这样的

webviewcontroller

late WebViewController _webViewController;

全面实施,

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:universal_html/html.dart' as html;
import 'package:webview_flutter/webview_flutter.dart';

class MyWebApp extends StatefulWidget {
  const MyWebApp({Key? key}) : super(key: key);

  @override
  State<MyWebApp> createState() => _MyWebAppState();
}

class _MyWebAppState extends State<MyWebApp> {
  final url =
      "https://accounts.google.com/o/saml2/initsso?idpid=C02qtgmcd&spid=859837136968&forceauthn=false";

  late WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Web Application"),
      ),
      body: WebView(
        initialUrl: url,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController controller) {
          _webViewController = controller;
        },
        javascriptChannels: <JavascriptChannel>{
          JavascriptChannel(
            name: 'PrintResponse',
            onMessageReceived: (JavascriptMessage message) {
              final receivedData = json.decode(message.message);
              print(receivedData); // Print the received data in the console
              // Handle the received data as needed
            },
          ),
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          if (_webViewController != null) {
            await _webViewController.evaluateJavascript(
                'window.postMessage(JSON.stringify(document.body.innerText))');
          }
        },
        child: const Icon(Icons.send),
      ),
    );
  }
}

此更新的代码利用

WebView
中的
webview_flutter
在 Flutter 应用程序中加载 URL。它设置一个 JavascriptChannel 来接收来自 Web 内容的消息。当按下浮动操作按钮时,它会评估 JavaScript 以通过
window.postMessage
发送网页内容。

© www.soinside.com 2019 - 2024. All rights reserved.