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

kse8i1jr  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(175)

在我的代码中,我已经在Web平台上启动了URL,也得到了响应,我无法从Web端获取和打印响应。
这是我的简单代码:

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"}


谁能帮我在控制台中获取并打印响应?

bvjveswy

bvjveswy1#

尝试使用listner来监听从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_flutter中的WebView在Flutter应用中加载URL。它设置了一个Javascript通道来接收来自Web内容的消息。当按下浮动操作按钮时,它会评估JavaScript以通过window.postMessage发送网页内容。

相关问题