来获取。

使用dio接收流式传输的文字可以通过使用dio的stream方法来实现,具体代码如下:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class StreamTextPage extends StatefulWidget {
  @override
  _StreamTextPageState createState() => _StreamTextPageState();
}

class _StreamTextPageState extends State<StreamTextPage> {
  String _text = '';

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

    _getTextStream().listen((data) {
      setState(() {
        _text = utf8.decode(data);
      });
    });
  }

  Stream<List<int>> _getTextStream() async* {
    final dio = Dio();
    final response = await dio.get('http://127.0.0.1:9000/?content=%E7%BB%99%E6%88%91%E5%86%99%E4%B8%80%E7%AF%87300%E5%AD%97%E7%9A%84%E6%96%87%E7%AB%A0%EF%BC%8C%E5%85%B3%E4%BA%8E%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD', options: Options(responseType: ResponseType.stream));

    yield* response.data.stream();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stream Text'),
      ),
      body: Center(
        child: Text(_text),
      ),
    );
  }
}

在上面的代码中,我们通过使用dio的stream方法来获取流式传输的数据,然后使用StreamBuilder来实时更新Text的内容。需要注意的是,在获取数据时需要设置options的responseType为ResponseType.stream,否则会无法获取到流式传输的数据

flutter使用dio接收流式传输的文字http1270019000content=E7BB99E68891E58699E4B880E7AF87300E5AD97E79A84E69687E7ABA0EFBC8CE585B3E4BA8EE4BABAE5B7A5E699BAE883BD并实时显示到一个text的组件文字的获取使用方法来获取而不是直接通过变量

原文地址: https://www.cveoy.top/t/topic/d1jS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录