I'm getting error. i want to update time after time being selected. as i'm new to flutter i'm unable to understand the flutter. I'm leaving pages that i've worked.
Main.dart
import 'package:flutter/material.dart';
import 'pages/choose_location.dart';
import 'pages/home.dart';
import 'pages/loading.dart';
void main() => runApp(MaterialApp(
initialRoute: '/loading', // Change the initialRoute to a valid route
routes: {
'/loading': (context) => Loading(),
'/home': (context) => const Home(),
'/location': (context) => const ChooseLocation(),
},
// Add a home argument for the default route (optional)
home: Loading(), // You can choose a different widget if needed
));
pages/world_time.dart
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
class WorldTime {
String location;
String flag;
String url;
String time;
bool isDaytime;
WorldTime({
required this.location,
required this.flag,
required this.url,
required this.time,
required this.isDaytime,
});
Future<void> getTime() async {
try {
var uri = Uri.http('worldtimeapi.org', '/api/timezone/$url');
var response = await get(uri);
Map data = jsonDecode(response.body);
// Getting properties from data
String dateTime = data["datetime"];
String offset = data["utc_offset"].substring(1, 3);
// Create datetime object
DateTime now = DateTime.parse(dateTime);
now = now.add(Duration(hours: int.parse(offset)));
isDaytime = now.hour > 6 && now.hour < 20 ? true : false;
time = DateFormat.jm().format(now);
} catch (e) {
print('Caught error: $e');
time = 'Could not get time data';
}
}
}
WorldTime instance = WorldTime(
location: 'berlin',
flag: 'germany',
time: '',
url: 'Europe/Berlin',
isDaytime: true, // Set isDaytime here
);
pages/home.dart
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
Map data = {};
@override
Widget build(BuildContext context) {
data = data.isNotEmpty ? data : ModalRoute.of(context)?.settings.arguments as Map; // Corrected type casting
print(data);
//set background
Color? bgColor = data['isDaytime'] ? Colors.blue : Colors.indigo[700];
return Scaffold(
backgroundColor: bgColor,
body: SafeArea(
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/day.png'),
fit: BoxFit.fill,
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(0.0,120.0,0.0,0.0),
child: Column(
children: [
TextButton.icon(
onPressed: () async {
dynamic result = await Navigator.of(context).pushNamed('/location'); // Corrected route name
setState(() {
data = {
'time': result['time'],
'location': result['location'],
'isDayTime': result['isDayTime'],
'flag': result['flag'],
};
});
},
label: const Text('Choose Location',
style: TextStyle(color: Colors.white),),
icon: const Icon(
Icons.edit_location,
color: Colors.white,
),
),
const SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['location'],
style: const TextStyle(
fontSize:28.0,
letterSpacing:2.0,
color: Colors.white,
),
)],
),
const SizedBox(height: 20.0),
Text(
data['time'],
style: const TextStyle(
fontSize: 66.0,
color: Colors.white,
),
)
],
),
),
),
),
);
}
}
pages/loading.dart
import 'package:flutter/material.dart';
import 'package:world_time/services/world_time.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class Loading extends StatefulWidget {
@override
State<Loading> createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
String time = 'loading';
bool isDaytime = true; // Initialize isDaytime as true or false
Future<void> setupWorldTime() async {
WorldTime instance = WorldTime(
location: 'Berlin',
flag: 'germany.png',
time: time,
url: 'Europe/Berlin',
isDaytime: isDaytime, // Set isDaytime here
);
await instance.getTime();
Navigator.pushReplacementNamed(context, '/home', arguments: {
'location': instance.location,
'flag': instance.flag,
'time': instance.time,
'isDaytime': instance.isDaytime,
});
print(instance.time);
setState(() {
time = instance.time;
});
}
@override
void initState() {
super.initState();
setupWorldTime();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[900],
body: const Center(
child: SpinKitFadingCube(
color: Colors.white,
size: 50.0,
),
),
);
}
}
pages/choose_location
import 'package:flutter/material.dart';
import 'package:world_time/services/world_time.dart';
class ChooseLocation extends StatefulWidget {
const ChooseLocation({Key? key}) : super(key: key);
@override
State<ChooseLocation> createState() => _ChooseLocationState();
}
class _ChooseLocationState extends State<ChooseLocation> {
List<WorldTime> locations = [
WorldTime(location: 'London', flag: 'uk.png', url: 'Europe/London', time: '', isDaytime: true),
WorldTime(location: 'Athens', flag: 'greece.png', url: 'Europe/Berlin', time: '', isDaytime: true),
WorldTime(location: 'Cairo', flag: 'egypt.png', url: 'Africa/Cairo', time: '', isDaytime: true),
WorldTime(location: 'Nairobi', flag: 'kenya.png', url: 'Africa/Nairobi', time: '', isDaytime: true),
WorldTime(location: 'Chicago', flag: 'usa.png', url: 'America/Chicago', time: '', isDaytime: true),
WorldTime(location: 'New York', flag: 'usa.png', url: 'America/New_York', time: '', isDaytime: true),
WorldTime(location: 'Seoul', flag: 'south_korea.png', url: 'Asia/Seoul', time: '', isDaytime: true),
WorldTime(location: 'Jakarta', flag: 'indonesia.png', url: 'Asia/Jakarta', time: '', isDaytime: true),
];
void updateTime(index) async {
WorldTime instance = locations[index];
await instance.getTime();
print(instance.location);
// Navigate to the home screen
// ignore: use_build_context_synchronously
Navigator.pop(context, {
'location': instance.location,
'flag': instance.flag,
'time': instance.time,
'isDaytime': instance.isDaytime,
});
}
@override
Widget build(BuildContext context) {
print('build function run');
return Scaffold(
backgroundColor: Colors.green,
appBar: AppBar(
backgroundColor: Colors.blue[900],
title: const Text('Choose a Location'),
centerTitle: true, // Center the title
elevation: 0,
),
body: ListView.builder(
itemCount: locations.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0, horizontal: 4.0),
child: Card(
child: ListTile(
onTap: () {
updateTime(index);
},
title: Text(locations[index].location),
leading: CircleAvatar(
backgroundImage: AssetImage('assets/${locations[index].flag}'),
),
),
),
);
},
),
);
}
}
this is my homepage homepage while i'm tapping going to choose location page chooselocation while i'm choosing the city it should update it on home page but throwing me some error like this enter image description here
In
home.dart
where you dosetState
you havethis needs to be
Notice the capital
T
that you have