Flutter:Api 请求处理时间太长

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

我正在尝试在我的 flutter 应用程序中发出 API 请求,但需要花费太多时间来处理,例如 15-25 秒。当我在 Postman 上运行相同的请求时,它工作正常,只需要 200 到 650 毫秒。我尝试使用diohttp 和 http 客户端,但结果几乎相同。下面是我的代码。

import 'package:http/http.dart' as http;
import 'package:dio_http/dio_http.dart';

void main() {
    WidgetsFlutterBinding.ensureInitialized();
    runApp(MyApp());
}

class MyApp extends StatelessWidget {
    MyApp({super.key});

    Dio dioRest = Dio(
        BaseOptions(
        baseUrl: baseURL,
        headers: {
            HttpHeaders.contentTypeHeader: ContentType.json.value,
        },
    ),
);

@override
Widget build(BuildContext context) {
    return MaterialApp(
    title: 'MYAPP',
    home: Scaffold(
        appBar: AppBar(title: Text("Home page")),
        body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
            MaterialButton(
                child: Text("Go to my profile"),
                color: Theme.of(context).primaryColor,
                onPressed: () async{
                    await getAllContentList();
                }),
            MaterialButton(
                child: Text("Go to Accounts"),
                color: Theme.of(context).primaryColor,
                onPressed: () async{
                    await getAllContentListHttp();
                }),
            ],
        ),
        ),
    ),
    );

}

Future<List<dynamic>> getAllContentList() async {
    try {
        print('Api Started');
        var result = await dioRest.post(baseURL+'secured/v/getAllContentList', options: Options(
            headers: {
            'Authorization': 'bearer $token',
            'Content-Type': 'application/json',
            },
        ));
        print('API result :: $result');
        if (result.statusCode == 200) {
            print('API result decoded :: ${jsonDecode(result.data)}');
            return jsonDecode(result.data);
        }
        throw DioError(requestOptions: result.requestOptions);
    } on DioError catch (error) {
        if (error.response!.statusCode! >= 400) {
            throw AccessTokenException(message: "Token invalid or expired");
        }
        var businessError = BusinessError.fromJson(error.response?.data);
        throw BusinessException(businessError, statusCode: error.response?.statusCode);
    } catch (error) {
        throw Error();
    }
}

    Future<List<dynamic>> getAllContentListHttp() async {
        try {
            print('Api Started');
            Map<String, String> requestHeaders = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer $token',
            };
            String stUrl = baseURL+'protected/users/getAllActiveStreamList';
            final response = await http.post(Uri.parse(baseURL+'secured/v/getAllContentList'), headers: requestHeaders);
            print('API result :: $response');
            if (response.statusCode == 200) {
                print('API result decoded :: ${jsonDecode(response.body)}');
                return jsonDecode(response.body);
            }
            throw AccessTokenException(message: "!!!Sorry");
        } on DioError catch (error) {
            if (error.response!.statusCode! >= 400) {
                throw AccessTokenException(message: "Token invalid or expired");
            }
            var businessError = BusinessError.fromJson(error.response?.data);
            throw BusinessException(businessError, statusCode: error.response?.statusCode);
        } catch (error) {
            throw Error();
        }
    }
 }

使用的版本:

http: ^0.13.5
dio_http: ^5.0.4
flutter http request dio
1个回答
0
投票

Dio 本身确实很慢,因为对请求正文和标头进行了一些额外的处理。

Http包的使用有微妙之处。例如,创建http.client需要很长时间。 详情请看这里

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