Home > database >  Flutter setState vs snapshot
Flutter setState vs snapshot

Time:10-07

i would like to know whats the diffrence between using setState and snapshot when fetching apis for example the way i fetch the apis is like the following

Widget text = Container;
Future<AnyClass> fetch() async{
final response = await http
  .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
var result = AnyClass.fromJson(jsonDecode(response.body));
setState(()=> text = result.title)
}
 @override
 Widget build(BuildContext context) {
 return Contianer(child:text)
 }

there is another way which uses the snapshot to featch the data instead of using state like the following

Future<Album> fetchAlbum() async {   final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

    return Album.fromJson(jsonDecode(response.body));

} @override   void initState() {
    super.initState();
    futureAlbum = fetchAlbum();   }   @override   Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data!.title);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }

              // By default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );   }

so i would like to know what are the diffrence between these two methods. Thanks

CodePudding user response:

None, you can check the FutureBuilder source code to see that is does exactly the same: call setState when it has a response.

The advantage of FutureBuilder are:

  • Easy handling of the different state (loading, loaded, failure)
  • You don't have to create a StatefulWidget, which means less line of code
  • Related