gpt4 book ai didi

dart - Flutter:如何一次又一次停止不必要地渲染 "Widget build()"?

转载 作者:IT王子 更新时间:2023-10-29 07:21:00 24 4
gpt4 key购买 nike

这是 Flutter 中的一个小型 POC,其中我的 build() 函数被一次又一次地调用。

如果没有任何循环,这完全出乎意料,经过大量研究,我也在 initState() 中调用 “Future”

但是仍然面临着同样的问题

预先感谢您的宝贵时间!

What have I tried..

import 'package:flutter/material.dart';

//http_request
import 'package:http/http.dart' as http; //to handle the http request
// import 'dart:async'; // for async functions
import 'dart:async' show Future;
import 'dart:convert'; //to convert the http response in JSON formate

import 'HomePage.dart';

class Reports extends StatefulWidget {
@override
_Reports createState() => _Reports();
}

class _Reports extends State<Reports> {
static String url = "Some Url";
String _response = "abc";
@override
void initState() {
super.initState();
getTradeName_dropdown_ITR_Computation_DATA();
}

@override
Widget build(BuildContext context) {

print('body');

return Scaffold(
body: Container(
child: new Text(_response),
),
);
}

Future getTradeName_dropdown_ITR_Computation_DATA() async {
try {
http.Response response =
await http.get("http://" + url );
if (this.mounted) {
setState(() {

String jsonTradeName_dropdown = response.body;
_response = jsonTradeName_dropdown;
});
}
} on Exception {
setState(() {
_response = "Some error occored. Please Try again...";
});
}
}
}

output:

I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body
I/flutter ( 5760): body

最佳答案

你犯了几个错误,这是正确的代码。您应该使用 String 而不是 Text 小部件来显示响应。

class _Reports extends State<Reports> {
static String url = "url";
String _response = "abc";
@override
void initState() {
super.initState();
getTradeName_dropdown_ITR_Computation_DATA();
}

@override
Widget build(BuildContext context) {

print('body');

return Scaffold(
body: Container(
child: new Text(_response),
),
);
}

Future getTradeName_dropdown_ITR_Computation_DATA() async {
try {
http.Response response =
await http.get("url_goes_here");

if (this.mounted) {
setState(() {
String jsonTradeName_dropdown = response.body;
_response = jsonTradeName_dropdown;
});
}
} on Exception {
setState(() {
_response = "Some error occored. Please Try again...";
});
}
}
}

关于dart - Flutter:如何一次又一次停止不必要地渲染 "Widget build()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com