Reputation: 1366
This is a small POC in Flutter, where my build() function is being called again and again.
This was not expected at all without any loops and after a lot of research, I am calling "Future" in initState() as well.
But still facing the same issue.
Thank you in advance for time!
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
Upvotes: 3
Views: 3300
Reputation: 44066
The proper model for understanding build() is that you should imagine it is being called sixty times a second. So your build() routine should be fast and idempotent.
In practice, there are optimizations made by the framework so that it isn't called except when needed, but you shouldn't view excessive calls to build() as a failure.
Upvotes: 1
Reputation: 267584
You were making couple of mistakes, here is the correct code. You should use a String
instead of a Text
widget to show the response.
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...";
});
}
}
}
Upvotes: 1