I am trying to create a program to display the time. When I try to display the time using a Text widget flutter throws an exception “Expected a value of type ‘String’, but got one of type ‘Null'”
I have the following dart files-:
1. main.dart
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_worldtime/pages/chose_location.dart';
import 'package:flutter_worldtime/pages/home.dart';
import 'package:flutter_worldtime/pages/loading.dart';
void main() => runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => Loading(),
'/home': (context) => Home(),
'/location': (context) => chooseLocation()
},
));
2.home.dart
// ignore_for_file: prefer_const_constructors
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
Map data = {};
@override
Widget build(BuildContext context) {
Map? data = ModalRoute.of(context)?.settings.arguments as Map?;
if (kDebugMode) {
print(data);
}
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(0,120.0,0,0),
child: Column(
children: <Widget>[
TextButton.icon(
onPressed: (){
Navigator.pushNamed(context, '/location');
},
icon: Icon(Icons.edit_location),
label: Text('edit location'),
),
SizedBox(height: 20.0,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data?['location'],
style: TextStyle(
fontSize: 28.0,
letterSpacing: 2.0,
),
)
],
),
SizedBox(height: 20.0,),
Text(
data?['time'],
style: TextStyle(
fontSize: 66.0
),
)
],
),
) )
);
}
}
3.loading.dart
import 'package:flutter/material.dart';
import 'package:flutter_worldtime/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: 'Berlin', flag: 'germany.png', url: 'Europe/Berlin');
await instance.getTime();
//print(instance.time);
// ignore: use_build_context_synchronously
Navigator.pushReplacementNamed(context, '/home', arguments: {
'location': instance.location, 'flag': instance.flag, 'time': instance.time
});
}
@override
void initState() {
super.initState();
setupWorldTime();
}
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child: SpinKitFadingCircle(
color: Colors.white,
size: 50.0,
),
)
);
}
}
4.world_time.dart
import 'package:flutter/foundation.dart';
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
class WorldTime {
String location; //location name for the UI
String time=''; //time in that location
String flag; //url to an asset flag icon
String url; //location url for API endpoint
WorldTime({ required this.location, required this.flag, required this.url});
Future<void> getTime() async {
try{
//make the request
Response response = await get(Uri.parse('https://worldtimeapi.org/api/timezone/$url'));
Map data = jsonDecode(response.body);
//print(data);
//get properties from data
String datetime = data['datetime'];
String offsetHour = data['utc_offset'].substring(1,3);
String offsetMinutes = data['utc_offset'].substring(4,6);
//print(datetime);
//print(offset_hour);
//print(offset_minutes);
//create a datetime object
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offsetHour),minutes: int.parse(offsetMinutes)));
//print(now);
time = DateFormat.jm().format(now); //set the time property
}
catch (e) {
if (kDebugMode) {
print('caught error: $e');
}
time = 'could not get time data';
}
}
}
I was trying to display the time and location of the place. I used the Navigator to change to the home screen from loading screen, and then used ModalRoute to take the arguments.
The exception is thrown on the two Text widgets in the home.dart file. it is displayed on the loading screen, but then is replaced by the home.dart screen which still displays the TextButton and Text widgets as expected.
this is the full error that is displayed on the debug console-
The following TypeErrorImpl was thrown building Home(dirty, dependencies: [_ModalScopeStatus],
state: _HomeState#96849):
Expected a value of type ‘String’, but got one of type ‘Null’