'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 1:[1]
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),
),
);
}
}
Solution 2:[2]
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}');
}
},
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nikitwei |
| Solution 2 | Mustafa Raza |
