1

I have multiple tabs. For an example, I have two tabs, tab 1 and tab 2. At tab 1 there is a future that fetch my data, then I go to tab 2 and back again to tab 1 but the future is running again. Well, I am trying to use

 bool get wantKeepAlive => true;

here is my script

  Future<List<HotProducts>> _loadHotProducts;
  @override
  void initState() {
    _loadHotProducts = fetchHotProducts(http.Client());
    super.initState();
  }


      @override
          Widget build(BuildContext context) {
            super.build(context);
            SystemChrome.setPreferredOrientations([
              DeviceOrientation.portraitUp,
              DeviceOrientation.portraitDown,
            ]);
               ------------
           }

    Widget populateHotProduct() {
    return FutureBuilder<List<HotProducts>>(
      future:this._loadHotProducts,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting &&
            snapshot.hasError == false) {
          return Center(child: CircularProgressIndicator());
        } else if (snapshot.connectionState == ConnectionState.waiting &&
            snapshot.hasError == true) {
          return error_();
        } else if (snapshot.connectionState == ConnectionState.done &&
            snapshot.hasError == true) {
          return error_();
        } else if(snapshot.hasError == true){
          return error_();
        } else{
          return HotProductsLists(hotlist: snapshot.data);
        }
      },
    );
  }
 Future<List<HotProducts>> fetchHotProducts(http.Client client) async {
    final response = await http.post(Configuration.url + "api/getHotProducts");
    if (response.statusCode < 200 || response.statusCode > 300) {
      throw new Exception('Failed to fetch data');
    } else {

      return compute(parseHotProducts, response.body);
    }
  }

  static List<HotProducts> parseHotProducts(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<HotProducts>((json) => HotProducts.fromJson(json)).toList();
  }

One thing, when i try to open another screen with

 Navigator.push(context, new MaterialPageRoute(
                builder:  (BuildContext context) {
                 return  ProductDetailPage(data: newlist[index]);
                }
));

and going back to tab 1, my future is not running again.

So how can I fix my problem, thanks in advance.

Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
Boby
  • 1,131
  • 3
  • 20
  • 52
  • 1
    Refer https://stackoverflow.com/questions/52249578/how-to-deal-with-unwanted-widget-build and https://medium.com/saugo360/flutter-my-futurebuilder-keeps-firing-6e774830bc2 . Hope it helps. – Aman Kataria Jul 18 '19 at 14:03

0 Answers0