await http.get(url) does not work even in StatefulWidget - flutter

2 days ago, I asked the solution of my problem in this post and got answer to make another statefulwidget and use http codes. So my code became :
class _post_openState extends State<post_open> {
void initState() {
super.initState();
// Enable virtual display.
if (Platform.isAndroid) WebView.platform = AndroidWebView();
// else if(Platform.isIOS)WebView.platform =
}
#override
Future <String> _scrap_title(url_received) async
{
var elements;
url_received = url_received.split(' ')[-1];
if (url_received.split(':')[0] !='https')
url_received = 'https://' + url_received;
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
print(url_received);
bool suc = false;
// Future.delayed(Duration.zero,() async {
print('response init');
if (url_received == '' || url_received == ' ') return 'No reference';
final url = Uri.parse(url_received);
print('response parsed');
final resp = await http.get(url);
print('response on');
print(resp.statusCode);
if (resp.statusCode == 200) {
dom.Document doc = parser.parse(resp.body);
elements = doc.querySelector('title');
suc = true;
}
//}
//);
return Future.value(elements!.text);
}
Widget build(BuildContext context){
String reference = widget.data_received[5];
bool leftright = widget.data_received[0];
String content = widget.data_received[1];
String writer = widget.data_received[2];
int like = widget.data_received[3];
int shared = widget.data_received[4];
print(widget.data_received);
print('**************************************');
void Function()? _showWeb(String title, String url)
{
showDialog(
context: context,
builder: (context) {
return Container(
height: MediaQuery.of(context).size.height*0.9,
width: MediaQuery.of(context).size.width*0.95,
padding: EdgeInsets.symmetric(horizontal: 3),
//
child:
Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0)
), //this right here
child:
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.symmetric(vertical: 10)),
Text(title),
Padding(padding: EdgeInsets.symmetric(vertical: 3)),
Container(height:2,color:Colors.brown),
Container(
height: MediaQuery.of(context).size.height*0.7,
width: MediaQuery.of(context).size.width*0.9,
padding: EdgeInsets.symmetric(horizontal: 5),
child:
Expanded(
child:WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
),
),
),
Container(height:2,color:Colors.brown),
Padding(padding: EdgeInsets.symmetric(vertical: 3)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton.icon(onPressed: (){
setState(){
};
}, icon:Icon(Icons.thumb_up_alt_outlined),label: Text('like'),style: TextButton.styleFrom(primary: Colors.brown)),
GestureDetector(
onTap: (){
Navigator.pop(context);
},
child:Container
(
width: MediaQuery.of(context).size.width*0.4,
height: 30,
color:Colors.amber,
child:Text('Back',style: TextStyle(fontSize:20,color: Colors.white),
textAlign: TextAlign.center,)
),
),
TextButton(onPressed: (){
setState(){
};
}, child: Icon(Icons.share),style: TextButton.styleFrom(primary: Colors.brown)),
],
),
],
)
)
);
});
}
return
Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 1.0,
),
body:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 40,
width: 40,
child:
TextButton(onPressed: () {
Navigator.pop(context);
},
style: TextButton.styleFrom(primary: Colors.brown,),
child: Icon(Icons.arrow_back)
),
),
),
Padding(padding: EdgeInsets.symmetric(vertical: 5)),
FutureBuilder<String>(
future: _scrap_title(reference),
builder: (BuildContext context, AsyncSnapshot snapshot){
print('snapshot status'+ snapshot.hasData.toString());
if (snapshot.hasData == false) {
return CircularProgressIndicator();
}
else
return GestureDetector(onTap: (){
_showWeb(writer, reference);
},
child:Text(snapshot.data,style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),),
);
}),
Padding(padding: EdgeInsets.symmetric(vertical: 5)),
Container(
height:1,
color: Colors.brown,
),
Padding(padding: EdgeInsets.symmetric(vertical: 5)),
Text(content,style: TextStyle(color:Colors.black87,fontSize: 15)),
]
)
);
}
}
But strangely, testing by print told me that this class does not even call _scrap_title.
I am having confusion of understanding lifecysle of widget/future/async and so on. Why do I keep failing to scrap html title of a web ? PLEASE somebody give me solution. Thank you so much.

Can you try replacing #override
///#override remove it
Future <String> _scrap_title(url_received) async
{....}
#override //add it here
Widget build(BuildContext context){
also better practice put variable outside the build method, you can use initState or use late
late String reference = widget.data_received[5];
late bool leftright = widget.data_received[0];
....
#override
Widget build(BuildContext context){
More about StatefulWidget

Related

How to wait for a request to complete using ObservableFuture?

When I transition to a screen where I get a list of information via an API, it initially gives an error:
_CastError (Null check operator used on a null value)
and only after loading the information, the screen is displayed correctly.
I am declaring the variables like this:
#observable
ObservableFuture<Model?>? myKeys;
#action
getKeys() {
myKeys = repository.getKeys().asObservable();
}
How can I enter the page only after loading the information?
In button action I tried this but to no avail!
await Future.wait([controller.controller.getKeys()]);
Modular.to.pushNamed('/home');
This is the page where the error occurs momentarily, but a short time later, that is, when the api call occurs, the data appears on the screen.
class MyKeyPage extends StatefulWidget {
const MyKeyPage({Key? key}) : super(key: key);
#override
State<MyKeyPage> createState() => _MyKeyPageState();
}
class _MyKeyPageState
extends ModularState<MyKeyPage, KeyController> {
KeyController controller = Modular.get<KeyController>();
Widget countKeys() {
return FutureBuilder(
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
final count =
controller.myKeys?.value?.data!.length.toString();
if (snapshot.connectionState == ConnectionState.none &&
!snapshot.hasData) {
return Text('..');
}
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 1,
itemBuilder: (context, index) {
return Text(count.toString() + '/5');
});
},
future: controller.getCountKeys(),
);
}
#override
Widget build(BuildContext context) {
Size _size = MediaQuery.of(context).size;
return controller.getCountKeys() != "0"
? TesteScaffold(
removeHorizontalPadding: true,
onBackPressed: () => Modular.to.navigate('/exit'),
leadingIcon: ConstantsIcons.trn_arrow_left,
title: '',
child: Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(left: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Keys',
style: kHeaderH3Bold.copyWith(
color: kBluePrimaryTrinus,
),
),
countKeys(),
],
),
),
),
body: Observer(builder: (_) {
return Padding(
padding: const EdgeInsets.only(bottom: 81),
child: Container(
child: ListView.builder(
padding: EdgeInsets.only(
left: 12.0,
top: 2.0,
right: 12.0,
),
itemCount:
controller.myKeys?.value?.data!.length,
itemBuilder: (context, index) {
var typeKey = controller
.myKeys?.value?.data?[index].type
.toString();
var id =
controller.myKeys?.value?.data?[index].id;
final value = controller
.myKeys?.value?.data?[index].value
.toString();
return GestureDetector(
onTap: () {
.
.
},
child: CardMeyKeys(
typeKey: typeKey,
value: value!.length > 25
? value.substring(0, 25) + '...'
: value,
myKeys: pixController
.minhasChaves?.value?.data?[index].type
.toString(),
),
);
},
),
),
);
}),
bottomSheet: ....
)
: TesteScaffold(
removeHorizontalPadding: true,
onBackPressed: () => Modular.to.navigate('/exit'),
leadingIcon: ConstantsIcons.trn_arrow_left,
title: '',
child: Container(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(left: 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'...',
style: kHeaderH3Bold.copyWith(
color: kBluePrimaryTrinus,
),
),
],
),
),
),
body: Padding(
padding: const EdgeInsets.only(bottom: 81),
child: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
'assets/images/Box.png',
fit: BoxFit.cover,
width: 82.75,
height: 80.91,
),
SizedBox(
height: 10,
),
],
),
), //Center
),
),
bottomSheet: ...
);
}
List<ReactionDisposer> disposers = [];
#override
void initState() {
super.initState();
controller.getKeys();
}
#override
void dispose() {
disposers.forEach((toDispose) => toDispose());
super.dispose();
}
}
Initially the error occurs in this block
value: value!.length > 25
? value.substring(0, 25) + '...'
: value,
_CastError (Null check operator used on a null value)
I appreciate if anyone can help me handle ObservableFuture correctly!
You need to call the "future" adding
Future.wait
(the return type of getKeys) keys=await Future.wait([
controller.getKeys();
]);
The problem is your getKeys function isn't returning anything, so there's nothing for your code to await. You need to return a future in order to await it.
Future<Model?> getKeys() {
myKeys = repository.getKeys().asObservable();
return myKeys!; // Presumably this isn't null anymore by this point.
}
...
await controller.controller.getKeys();
Modular.to.pushNamed('/home');

FutureBuilder shows [instance] instead of actual data

I want to download a list from firestore and display as a list in flutter widget. The data is successfully downloaded (proved by the print(cp.data()).
However, the result shown is [Instance of '_JsonQueryDocumentSnapshot'] instead of the actual carpark data.
Could anyone pls help point out what the bug is.
Thanks
class DownloadDataScreen extends StatefulWidget {
#override
_DownloadDataScreen createState() => _DownloadDataScreen();
}
class _DownloadDataScreen extends State<DownloadDataScreen> {
List<DocumentSnapshot> carparkList = []; //List for storing carparks
void initState() {
super.initState();
readFromFirebase();
}
Future readFromFirebase() async {
// await FirebaseFirestore.instance
await FirebaseFirestore.instance
.collection('carpark')
.get()
.then((QuerySnapshot snapshot) {
snapshot.docs.forEach(
(DocumentSnapshot cp) {
carparkList.add(cp);
print('printing cp');
print(cp.data());
},
);
});
**return carparkList;**
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(
'Car Park',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: FutureBuilder(
future: readFromFirebase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = <Widget>[
const Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Column(
children: [
Text('Result: ${snapshot.data}'),
],
),
)
];
} else if (snapshot.hasError) {
children = <Widget>[
const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
children = const <Widget>[
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
),
Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: children,
),
);
},
),
);
}
}
First, you don't need to call the function from the init because you already use the FutureBuilder.
Also, you don't need to cast it because when the future completes, the async snapshot already would provide you a list of DocumentSnapshot in the data and the .doc propertie.
Like this:
FutureBuilder<QuerySnapshot>(
builder:(context,snapshot){
if(snapshot.hasData){
/// here your data
snapshot.data.docs;
}
)

How to Hide a card in flutter

I make one page to edit data by user.In this page I have two card.In the first card, I can see the user's picture.In the second card, I can see the user’s picture after selecting them from the phone or the picture they want to update.But now my problem is, how can I hide the first card if the second card appears after the user selects an image from the phone.I know it can be done by using Visibility in Java, but I'm a new filter developer and I don't know how to do it. I searched a lot and couldn't solve the problem.
Card 1:
child: Card(
child: new Column(
children: <Widget>[
Image.network(image, width: 385,height: 300,
fit: BoxFit.cover,
),
OutlineButton(
onPressed: chooseImage,
child: Text('Choose Image'),
),
])
),
Card 2:
Card(
child: SizedBox(
width: 400.0,
height: 300.0,
child: new Padding(
padding:
const EdgeInsets.only(top: 2.0, bottom: 2.0),
child: Expanded(flex: 1,
child: showImage(),
)
),
),
),
Full page:
class update_profilettt extends StatefulWidget {
var PostID;
update_profilettt({Key key, this.PostID}) : super(key: key);
#override
_update_profiletttState createState() => new _update_profiletttState(PostID);
}
class _update_profiletttState extends State<update_profilettt> {
MyPreferences _myPreferences = MyPreferences();
var PostID;
String uploadEndPoint;
_update_profiletttState(this. PostID);
Future<File> file;
String status = '';
String base64Image;
File tmpFile;
String errMessage = 'Error Uploading Image';
var data;
var _name = "";
// var _genderController = new TextEditingController();
var _nameController = new TextEditingController();
chooseImage() {
setState(() {
file = ImagePicker.pickImage(source: ImageSource.gallery);
});
setStatus('');
}
setStatus(String message) {
setState(() {
status = message;
});
}
startUpload() {
setStatus('Uploading Image...');
if (null == tmpFile) {
setStatus(errMessage);
return;
}
String NameImage =DateTime.now().millisecondsSinceEpoch.toString();
upload(NameImage);
}
upload(String NameImage) {
uploadEndPoint = 'http://xxxxxxx/up.php?id='+widget.PostID.toString();
print('yeyyyyddyy $uploadEndPoint');
http.post(uploadEndPoint, body: {
'id': widget.PostID.toString(),
}).then((result) {
setStatus(result.statusCode == 200 ? result.body : errMessage);
}).catchError((error) {
setStatus(error);
});
}
Widget showImage() {
return FutureBuilder<File>(
future: file,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
null != snapshot.data) {
tmpFile = snapshot.data;
base64Image = base64Encode(snapshot.data.readAsBytesSync());
return Flexible(
child: Card(
margin:EdgeInsets.all(10) ,
child: Image.file(
snapshot.data,
fit: BoxFit.cover,
),
),
);
} else if (null != snapshot.error) {
return const Text(
'Error Picking Image',
textAlign: TextAlign.center,
);
} else {
return const Text(
'',
textAlign: TextAlign.center,
);
}
},
);
}
Future<String> _ShowDialog(String msg) async {
return showDialog<String>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return new AlertDialog(
title: new Text('Rewind and remember'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text(msg),
],
),
),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _editData() async {
// String NameImage =DateTime.now().millisecondsSinceEpoch.toString();
var url = 'http://xxxxxxxxxx/up.php?id='+widget.PostID.toString();
var response = await http.post(url, body: {
'id': widget.PostID.toString(),
// "id": _userController.text,
"name": _nameController.text,
"image": base64Image,
// "gender": _genderController.text,
});
if (response.statusCode == 200) {
_ShowDialog("Updated Successfully");
} else {
_ShowDialog("Updated Failer");
}
//onEditedAccount();
//print(_adresseController.text);
}
_fetchData() async {final url = "http://xxxxxxxx/nhy.php?id=${widget.PostID}";
final response = await http.get(url);
if (response.statusCode == 200) {
final map = json.decode(response.body);
final videosMap = map["result"];
setState(() {
this.data = videosMap;
_name = data[0]['name'];
image = data[0]['image'];
// _gender = data[0]['gender'];
print(data);
});
}
}
#override
void initState() {
super.initState();
_fetchData();
}
#override
Widget build(BuildContext context) {
_nameController= new TextEditingController(text: _name);
if(chooseImage !=null){
}
return new Scaffold(
appBar: AppBar(
title: Text("Edit Post"),
),
body: new Center(
child: data == null
? new CircularProgressIndicator()
: new ListView(
children: <Widget>[
new Padding(
padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
child: Column(
children: <Widget>[
new Padding(
padding:
const EdgeInsets.only(top: 10.0, bottom: 10.0),
child: Expanded(flex: 1,
child: Container(
child: Card(
child: new Column(
children: <Widget>[
Image.network(image, width: 385,height: 300,
fit: BoxFit.cover,
),
OutlineButton(
onPressed: chooseImage,
child: Text('Choose Image'),
),
])
),
),
),
),
Card(
child: SizedBox(
width: 400.0,
height: 300.0,
child: new Padding(
padding:
const EdgeInsets.only(top: 2.0, bottom: 2.0),
child: Expanded(flex: 1,
child: showImage(),
)
),
),
),
Card (
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Container(
margin: EdgeInsets.all(4),
child: TextField(
maxLength: 10,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Name',
filled: true,
hintText: ''),
controller: _nameController,
),
),
SizedBox(
height: 5.0,
),
),
SizedBox(
height: 5.0,
),
),
),
),
),
SizedBox(
height: 5.0,
),
]
)
),
SizedBox(
width: double.infinity,
child: new FlatButton(
child: const Text('Update'),color: Colors.amber,
padding: EdgeInsets.fromLTRB(100, 18, 100, 18),
onPressed: () { _editData();
},
),
),
SizedBox(
height: 10.0,
),
],
),
)
],
),
));
}
}
There is a Visibility widget in flutter too you can wrap your card with it
Example
bool visibilityController = true;
true for visibile and false for not visible
so when select the card use setstate to toggle it.
setState(() {
});
Visibility(
visible: visibilityController,
child : //Your card
),
Hope this is what you wished for.
For your code
you can do this when your showimage() gets an image
Widget showImage() {
return FutureBuilder<File>(
future: file,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
null != snapshot.data) {
tmpFile = snapshot.data;
base64Image = base64Encode(snapshot.data.readAsBytesSync());
setState(() {
// added here
visibilityController = false;
});
return ........ your code

AppBar in flutter

I have designed a news application in flutter where I have an app bar with tabs following it. In the tabbarview I have a list of news. on click of the news, it will show details description and image of the news(as shown in the image). When I try to put the app bar in that file. Two app bar appears. What would the possible way sort it out?
Here is the code:
appBar: AppBar(
title: Text(""),
backgroundColor: Color(0xFF125688), //#125688 //FFFF1744
actions: <Widget>[
Container(
alignment: Alignment.topRight,
child: FlatButton(
onPressed: () {},
padding: EdgeInsets.fromLTRB(0, 10.0, 8.0, 0),
child: Text(
date,
style: TextStyle(
color: Colors.white,
),
)),
)
],
bottom: TabBar(
tabs: <Widget>[
Tab(text: "TOP-HEADLINES"),
Tab(text: "LATEST-NEWS"),
Tab(text: "SPORTS"),
Tab(text: "CRIME-NEWS"),
],
isScrollable: true,
),
),
body: TabBarView(children: [
TopHeadlines(),
LatestNews(),
Sports(),
CrimeNews(),
],
),
CODE FOR TOPHEADLINES()
class TopHeadlines extends StatefulWidget {
int index;
String value_image,value_description,value_title;
TopHeadlines({Key key,this.value_image,this.value_description,this.value_title,this.index}) : super(key:key);
#override
_topHeadlines createState() => _topHeadlines();
}
class _topHeadlines extends State<TopHeadlines> {
List<News> dataList = List();
bool _isLoading = false;
BuildContext context1;
Future<String> loadFromAssets() async {
DateTime oops = DateTime.now();
String d_date = DateFormat('ddMMyyyy').format(oops);
var url = 'https://www.example.com/json-12.json';
print(url);
var response = await http
.get('$url', headers: {"charset": "utf-8", "Accept-Charset": "utf-8"});
String utfDecode = utf8.decode(response.bodyBytes);
return utfDecode;
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadFromAssets();
String newStr = jsonString.substring(1, jsonString.length - 1);
print(newStr);
Map newStringMap = json.decode(newStr);
var list = new List();
newStringMap.forEach((key, value) {
list.add(value);
});
for (var newsList in list) {
var news = News.fromJson(newsList);
dataList.add(news);
}
print('This is the length' + dataList.length.toString());
print(dataList[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
DateTime oops = DateTime.now();
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Container(
child: _isLoading ? Center(
child: CircularProgressIndicator(),) :
ListView.builder(
itemCount: dataList.length, itemBuilder: (context, index) {
return SizedBox(
height: 130.0,
child: Card(
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: (){
// dataList;
Navigator.push(context, MaterialPageRoute(builder: (context) {
print(index);
return Newsdetail(value_image: dataList[index].image,value_description: dataList[index].description,value_title: dataList[index].title, );
}));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Image.network(
dataList[index].image,
height: 92.5,
width: 75.0,
)),
Expanded(
child: Text(
dataList[index].title,
style: TextStyle(
//title
fontSize: 15.0, color: Colors.grey,
),
),
)
],
),
),
),
],
),
),
);
},
),
));
}
}
Remove the appBars from these views:
TopHeadlines(),
LatestNews(),
Sports(),
CrimeNews(),
Only return the Content you want to display by return a Container or the widget you want to display

How to hit an API when time is 00:00 in Flutter?

I am working on my first Flutter App. There is an Activity/Screen which is showing a countdown time. I want, when time is 00:00 then hit an API.
I tried and search on it but i didn't find anything best about this problem.
Please tell me how to resolve this ?
Thank you.
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
String time;
String topicName;
Future<String> getTime() async{
final response = await http.post(Constant.TestTime,
body: {
"topic_id" : widget.valueTopicId,
});
Map<String,dynamic> respons = jsonDecode(response.body);
setState(() {
time=respons['test_time'];
topicName=respons['topic_name'];
controller = AnimationController(
vsync: this,
duration: Duration(minutes:int.parse(time) ,seconds: 00),
);
if (controller.isAnimating)
controller.stop();
else {
controller.reverse(
from: controller.value == 0.0
? 1.0
: controller.value);
}
});
print(respons.toString());
setState(() {
isLoading=false;
});
}
Widget _buildAppBar (BuildContext context){
return PreferredSize (preferredSize: Size.fromHeight(MediaQuery.of(context).size.height * 0.085),
child: AppBar(
backgroundColor: Colors.blue,
title: Text("Questions"),
centerTitle: true,
iconTheme: IconThemeData(
color: Colors.white
),
actions: <Widget>[
new Container(
margin: const EdgeInsets.only(top: 25.0, left: 25.0),
child: new Text(topicName,
style: TextStyle(color: Colors.white, fontSize: 26,
fontWeight: FontWeight.bold),),
),
SizedBox(width: 20),
new Padding(padding: EdgeInsets.all(20.0)),
new Padding(padding: EdgeInsets.only(bottom: 40, top: 50)),
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Align(
alignment: FractionalOffset.center,
child: AspectRatio(aspectRatio: 1.0,
child: Stack(
children: <Widget>[
Positioned.fill(child:
AnimatedBuilder(
animation: controller,
builder: (BuildContext context,
Widget child) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: CustomPaint(
painter: TimerPainter(
animation: controller,
backgroundColor: Colors.white,
color: Colors.blue,
),
),
);
},
),
),
Align(
alignment: FractionalOffset.center,
child: Column(
mainAxisAlignment: MainAxisAlignment
.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment
.center,
children: <Widget>[
AnimatedBuilder(
animation: controller,
builder: (BuildContext context,
Widget child) {
return Text(
timerString, style: TextStyle(
color: Colors.white),
);
}
)
],
),
)
],
),
)
),
),
],
)
)
],
) ,);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: onBackPressed,
child: isLoading
? Center(child: CircularProgressIndicator(),)
:MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
resizeToAvoidBottomPadding: false,
appBar: _buildAppBar(context),
body: Questions(widget.valueTopicId,widget.noOfQuestions,widget.difficulty,time),
)
),
);
}
}
Here i posted my code and an API getTime() is hitting on initState(). So, when my time is 00:00 then an another API should hit. I tried with FutureBuilder but it did not work. May be I did something wrong but so confusing in this.
You can user Timer, you need to import dart:async
Timer(Duration(seconds: 5), () {
getTime();
});
You, need to register your timer in initState.
Timer.periodic() will be executed at a particular duration after specified time.
Timer _timer;
#override
void initState()
{
_timer = Timer.periodic(
const Duration(seconds: 1), (Timer t) => handleAPICall(),
);
super.initState();
}
#override
void dispose()
{
_timer?.cancel();
super.dispose();
}
void handleAPICall()
{
// here you need to check if its time to make the API call.
// I am assuming that you will have some datetime that will tell you
// if duration time is 00:00
if(duration_time == 00:00) // you need to write your correct logic
{
// then, make the HTTP Call.
}
}