Flutter ,Dont Use Function in Future Builder

Yasin DALKILIÇ
2 min readMar 3, 2023

--

hello everyone, today we will talk about a future builder in a flutter. We are using a lot of future builders in flutter but there is one thing we need to pay attention to using functions in the future builders. If we use a function in the future builder, this function can be called more than once because it is included in the future builder, build function and every change on the screen calls the build method again, causing the function in the future builder to be called again.

Don't do this

class FutureDemoPage extends StatelessWidget {
/// Function that will return a
/// "string" after some time
/// To demonstrate network call
/// delay of [2 seconds] is used
///
/// This function will behave as an
/// asynchronous function
Future<String> getData() {
return Future.delayed(Duration(seconds: 2), () {
return "I am data";
// throw Exception("Custom Error");
});
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('Future Demo Page'),
),
body: FutureBuilder(
builder: (ctx, snapshot) {
// Checking if future is resolved or not
if (snapshot.connectionState == ConnectionState.done) {
// If we got an error
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error} occurred',
style: TextStyle(fontSize: 18),
),
);

// if we got our data
} else if (snapshot.hasData) {
// Extracting data from snapshot object
final data = snapshot.data as String;
return Center(
child: Text(
'$data',
style: TextStyle(fontSize: 18),
),
);
}
}

// Displaying LoadingSpinner to indicate waiting state
return Center(
child: CircularProgressIndicator(),
);
},

// Future that needs to be resolved
// inorder to display something on the Canvas
future: getData(),
),
),
);
}
}

Do this

If we put our Future Function into a variable and update the state or field, this function will only work once.

 Future<String> _value;

@override
initState() {
super.initState();
_value = getValue();
}

FutureBuilder<String>(
future: _value,
// other arguments
)

--

--

Yasin DALKILIÇ

Hi, My name is Yasin I am a Software Developer, I love so much researching and development 😊 Here is my youtube channel @webciyasin