Home > OS >  how I avoid FutureBuilder runs multiple times and duplicate the output List
how I avoid FutureBuilder runs multiple times and duplicate the output List

Time:04-15

I have a Future function that returns a List and I had the problem that kept duplicating... I solved it by setting an initState() as described here: Flutter FutureBuilder gets constantly called flutter-futurebuilder-gets-constantly-called

Now I need the Future function to be executed when I press a button, to do this I have created a list to which I add the FutureBuilder when I press the button, but I have removed the initState().

So now the duplication problem is back...

Does anyone know how I can make FutureBuilder run only once when I press the button?

I cannot attach the code because it is too long and complicated, I hope I was clear enough and that someone can help me. Thanks :)

CodePudding user response:

Hi maybe you can check my sample code below

class _MyHomePageState extends State<MyHomePage> {
  List<String> _myList = [];
  bool isLoading = false;

  setLoading()=>setState(()=>isLoading = !isLoading);
  
  Future<void> _myFunction()async{
    setLoading();
    await Future.delayed(const Duration(seconds:1));
    _myList.add("Some Text");
    setLoading();
  }

  @override
  initState(){
    _myFunction();
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            const Text('Your List:'),
            ..._myList.map((e)=> Text(e)),
            if(isLoading) const CircularProgressIndicator()
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed:()=> _myFunction(),
        child: const Icon(Icons.add),
      ),
    );
  }
}

CodePudding user response:

that's method never call function everytime. only then call when Page initState() is create, otherwise not Flutter FutureBuilder Constantly Called Thankyou

class _MyHomePageState extends State<MyHomePage> {

  Future<List<DataModal>> getFuture;

  @override
  void initState() {
    super.initState();
    getFuture = fetchData();
  }
  
  @override
   Widget build(BuildContext context) {

    return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),

    body: FutureBuilder<List<PostModalClass>>(
    future: getFuture,
    builder: (BuildContext context,    
       AsyncSnapshot<List<PostModalClass>>snapshot) {
       switch (snapshot.connectionState) {
         case ConnectionState.waiting: return Text('Loading....');
         default:
           if (snapshot.hasError)
              return Text('Error: ${snapshot.error}');
           else
          return Text('Result: ${snapshot.data}');
        }
      },
    ),
    );
  }
}
  • Related