Created
June 28, 2023 05:01
-
-
Save pmatatias/3dadbc210baaf70d405b75e5389c7ba8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:math'; | |
Future<String> apiCall() async { | |
print("apiCall is executed..."); | |
await Future.delayed(const Duration(seconds: 3)); | |
return Future.value("${Random().nextInt(100)} update"); | |
} | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
const MyHomePage({ | |
Key? key, | |
required this.title, | |
}) : super(key: key); | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
late Future<String> localFuture; | |
@override | |
void initState() { | |
localFuture = apiCall();// if you define as local state, it will not executed | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ | |
ElevatedButton( | |
onPressed: () { | |
print("update btn pressed"); | |
setState(() {}); | |
}, | |
child: const Text("update")), | |
FutureBuilder( | |
future: apiCall(), | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.waiting) { | |
return const Center(child: CircularProgressIndicator()); | |
} else { | |
return Text("apiCall : ${snapshot.data}"); | |
} | |
}), | |
FutureBuilder( | |
future: localFuture, | |
builder: (context, snapshot) { | |
if (snapshot.connectionState == ConnectionState.waiting) { | |
return const Center(child: CircularProgressIndicator()); | |
} else { | |
return Text("Local Future: ${snapshot.data}"); | |
} | |
}), | |
])), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment