Search code examples
listflutterfutureflutter-futurebuilder

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


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 :)


Solution

  • 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),
          ),
        );
      }
    }