I am following a tutorial and I am getting this error and have no idea what it means or why is it occurring. Also, my editor doesn’t show any problems in my code. Only two files are related to the problem and here are their code:
World Time:
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
class WorldTime {
String location;
String url;
String time = "";
String flag = "";
WorldTime({ required this.location, required this.url});
Future<void> getTime() async {
// getting info and decoding it
Response response = await get(
Uri.parse("http://worldtimeapi.org/api/timezone/$url"));
Map use = jsonDecode(response.body);
// extracting usefuls from it
String datetime = use['datetime'];
int offsetHours = int.parse(use['utc_offset'].substring(1, 3));
int offsetMinutes = int.parse(use['utc_offset'].substring(4, 6));
// converting into readable format
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: offsetHours, minutes: offsetMinutes));
time = (DateFormat.jm().format(now)).toString();
}
}
Loading file:
import 'package:flutter/material.dart';
import 'package:world_time/services/world_time.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class Loading extends StatefulWidget {
const Loading({super.key});
@override
State<Loading> createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupWorldTime() async {
WorldTime instance = WorldTime(location: "Kolkata", url: "Asia/Kolkata", );
await instance.getTime();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
Navigator.pushNamed(context, "/home");
return const Scaffold(
backgroundColor: Colors.blue,
body: SpinKitWanderingCubes(
color: Colors.green,
size: 50.0,),
);
}
}
I tried searching it on Google and many results but none of them was helpful to me. I also tried some tweaks in my code but that didn’t help too.
2
Answers
you are not allowed to push other page in build block.
the issue was here :
Solution you can use
FutureBuilder
or run the code inside didChangeDependciesthe code will called after page finished build.
to Your Building Another widget before current widget is building completed, In your code you are trying Navigating in build method, so build method is calling each time when changes occured .
If You want navigate to another page after certain operation is completed you can use as follows