flutter - 我可以使用颤振计算功能来http get吗?
问题描述
我需要在我的颤振应用程序中使用 http.get 或 http.post 从我的 API 服务器获取响应。
我需要做一些类似于Flutter app background use of the compute function的问题。
我想我可以在计算函数中解析我的响应 json,这没关系,是否可以在 http.get 请求中计算()一个函数?
这是因为我看到我的微调器 (CircularProgressIndicator) 在解析数据(已解决将解析函数放置在计算中)以及在 3G/4G 上执行请求时滞后,可能是由于网络性能不佳。
print(await calculate("aaaaa"));
Future<String> calculate(String foo) async {
var url = serverDomain+'/v1/search-event';
var body = json.encode({
"name": foo
});
// Lagging on await response??
final response = await http.post(url, headers:globalHeader, body:body);
return await compute(_isolate, response.body);
}
//Very cpu intensive operation, no lag
static String _isolate(String a){
var ab;
print(jsonDecode(a));
for (int i = 0; i < 999999; i++){
ab = i ^ 2;
}
return a;
}
我做错了什么?
解决方案
compute
可以在带有 HTTP 请求的 Future 中使用,并且http.post
不应阻塞 UI 线程。如何在屏幕上显示 CircularProgressIndicator?如果您能够为 HTTP 请求中使用的端点提供重现,这也会很有帮助。由于未提供端点,我尝试使用 Future.delayed 模拟 HTTP 请求对 Isolate 进行最小复制,以模拟其响应时间。
这是我显示/隐藏 ProgressIndicator 的方式。
void _runCalculate() {
/// show ProgressIndicator
setState(() {
showProgress = true;
});
calculate().then((value) {
debugPrint('calculate finished: $value');
/// Hide ProgressIndicator
setState(() {
showProgress = false;
});
});
}
我已经稍微修改了您的最小复制以模拟 HTTP 请求的响应延迟。
Future<bool> mockHttpRequest() async {
await Future.delayed(const Duration(seconds: 3));
return true;
}
Future<String> calculate() async {
// var url = serverDomain+'/v1/search-event';
// var body = json.encode({
// "name": foo
// });
// Lagging on await response??
debugPrint('mockHttpRequest start');
final response = await mockHttpRequest();
debugPrint('mockHttpRequest end: $response');
return await compute(_isolate, response);
}
//Very cpu intensive operation, no lag
static String _isolate(bool a) {
int ab = 0;
for (int i = 0; i < 999999; i++) {
ab = i ^ 2;
}
return ab.toString();
}
完整的复制
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var showProgress = false;
String? isolateResponse;
void _runCalculate() {
debugPrint('calculate start');
/// show ProgressIndicator
setState(() {
showProgress = true;
});
calculate().then((value) {
debugPrint('calculate finished: $value');
/// Hide ProgressIndicator
setState(() {
showProgress = false;
isolateResponse = value;
});
});
}
Future<bool> mockHttpRequest() async {
await Future.delayed(const Duration(seconds: 3));
return true;
}
Future<String> calculate() async {
// var url = serverDomain+'/v1/search-event';
// var body = json.encode({
// "name": foo
// });
// Lagging on await response??
debugPrint('mockHttpRequest start');
final response = await mockHttpRequest();
debugPrint('mockHttpRequest end: $response');
return await compute(_isolate, response);
}
//Very cpu intensive operation, no lag
static String _isolate(bool a) {
int ab = 0;
for (int i = 0; i < 999999; i++) {
ab = i ^ 2;
}
return ab.toString();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body:
Center(
child: showProgress
? const CircularProgressIndicator()
: Text('Isolate response: $isolateResponse'),
),
// }),
floatingActionButton: FloatingActionButton(
onPressed: _runCalculate,
tooltip: 'Run',
child: const Icon(Icons.play_arrow),
),
);
}
}
推荐阅读
- forms - 通过表单使用表单上的输入和另一个表中的数据更新表
- google-bigquery - 每月通过三个不同的查询获得 3 个最佳帖子
- javascript - 如何在 ExpressJs 路由器中使用精确匹配
- java - 将 SQL 语句转换为 JPA CriteriaBuilder 查询
- https - 使用来自 tomcat 的先前证书设置 consul https
- node.js - MongooseError:查询已执行
- javascript - 关闭 id links 中的移动菜单
- go - 如何在 go111MODULE=on 的另一个包中引用一个包
- keras - Tensorflow:不提供梯度的自定义损失函数
- git - 如何使用 .gitignore 忽略目录中除一个文件之外的所有内容?