Flutter:我如何一次又一次停止渲染“ Widget build()”?

时间:2019-04-12 08:14:58

标签: dart flutter

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

完全没有任何循环是无法预期的,经过大量研究,我也在initState()中称呼“ Future”

仍然仍面临同一问题

谢谢您的时间

  

我尝试了什么。

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...";
      });
    }
  }
}
  

输出:

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

2 个答案:

答案 0 :(得分:0)

您犯了几个错误,这是正确的代码。您应该使用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...";
      });
    }
  }
}

答案 1 :(得分:0)

理解build()的正确模型是您应该想象它每秒被调用60次。因此,您的build()例程应该快速且幂等。

在实践中,该框架做了一些优化,因此只有在需要时才调用它,但是您不应将对build()的过多调用视为失败。