user12456101
user12456101

Reputation:

How to fetch data only once when using FutureBuilder?

I have a fetch request and I am passing it as a future to FutureBuilder -

FutureBuilder(
    future: gettask(),
    builder: (context, snapshot){
        if(snapshot.hasData){

//           Stopwatch stopwatchbefore = new Stopwatch()..start();
//           print('futurebuilder executed in ${stopwatchbefore.elapsed}');

             return SingleChildScrollView(child: listViewWidget(snapshot.data));

        }else{
             return  Center(child: CircularProgressIndicator());
        }
    },
)

The method gettask() however, seems to be fetching events repeatedly. I tried to use https://pub.dev/packages/memoize and https://api.flutter.dev/flutter/package-async_async/AsyncMemoizer-class.html but i think they are deprecated since it says that AsyncMemoizer is undefined (no import option available).

I have also tried https://github.com/flutter/flutter/issues/11426#issuecomment-414047398 But i wanted to explore an option similar to memoizer.

are there any alternatives to fetching data only once (something similar to memoizer)?

Upvotes: 2

Views: 2757

Answers (2)

mtengineer
mtengineer

Reputation: 7

import 'dart:async';
import 'package:async/async.dart';

It worked for me...

Upvotes: -1

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15063

Use StatefulWidget, then create an Future variable (like _getTaskAsync) inside State.

Assign gettask() to that future variable in initState.

Then use that variable as argument to FutureBuilder(like future: _getTaskAsync)

Code:

class _MyStatefulWidgetState extends State<MyStatefulWidget> {

  Future _getTaskAsync;

  ...

  @override
  void initState() {
    _getTaskAsync = gettask();
    super.initState();
  }

  ...

    FutureBuilder(
      future: _getTaskAsync,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          //Stopwatch stopwatchbefore = new Stopwatch()..start();
          //print('futurebuilder executed in ${stopwatchbefore.elapsed}');

          return SingleChildScrollView(child: listViewWidget(snapshot.data));
        } else {
          return Center(child: CircularProgressIndicator());
        }
      },
    );

Refer the document

Upvotes: 7

Related Questions