Home > database >  type 'Null' is not a subtype of type 'String' error in Flutter
type 'Null' is not a subtype of type 'String' error in Flutter

Time:10-10

Question: I am building an world time app and i am getting an error that type 'Null' is not a subtype of type 'String'.i am using variable isdaytime to change the background image in the app according to the time of the country, at day time backgroung image will be day and at night the bg image will be of night. but it seems the string is getting Null somewhere. Please help me in solving the doubt

Error image

Main.dart

import 'package:flutter/material.dart';
import 'package:universal_time_app/pages/choose_location.dart';
import'package:universal_time_app/pages/home.dart';
import'package:universal_time_app/pages/loading.dart';


void main() => runApp(MaterialApp(
  initialRoute: '/home',
  routes: {
    '/':(context)=>Loading(),
    '/home':(context)=>Home(),
    '/location':(context)=>ChooseLocation(),
  },
));

Choose_location.dart

import 'package:path/path.dart';
import 'package:flutter/material.dart';
import'package:universal_time_app/services/universal_time.dart';
//import 'package:universal_time_app/pages/loading.dart';
//import 'package:universal_time_app/pages/home.dart';

class ChooseLocation extends StatefulWidget {
  const ChooseLocation({Key? key}) : super(key: key);

  @override
  _ChooseLocationState createState() => _ChooseLocationState();
}

List<UniversalTime> locations = [
  UniversalTime(url: 'Europe/London', location: 'London', flag: 'UK.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Europe/Athens', location: 'Athens', flag: 'Greece.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Africa/Cairo', location: 'Cairo', flag: 'Egypt.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Africa/Nairobi', location: 'Nairobi', flag: 'Kenya.png',time:'',isdaytime: 1),
  UniversalTime(url: 'America/Chicago', location: 'Chicago', flag: 'usa.png',time:'',isdaytime: 1),
  UniversalTime(url: 'America/New_York', location: 'New York', flag: 'usa.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Asia/Seoul', location: 'Seoul', flag: 'South_Korea.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Asia/Jakarta', location: 'Jakarta', flag: 'Indonesia.png',time:'',isdaytime: 1),
  UniversalTime(url: 'Asia/Kolkata', location: 'Delhi', flag: 'India.png',time:'',isdaytime: 1),
];

//void updateTime(snapshot,context);

void updateTime(index,context) async {
  //var instance = locations[index];
  UniversalTime instance = locations[index];
  await instance.getTime();
  //navigate to home screen

      Navigator.pop(context, {
        'location': instance.location,
        'flag': instance.flag,
        'time': instance.time,
        'isdaytime': instance.isdaytime
      });

}


class _ChooseLocationState extends State<ChooseLocation> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueGrey,
      appBar: AppBar(
        backgroundColor: Colors.greenAccent,
        title: Text('Choose a location'),
        centerTitle: true,
        elevation: 0,
      ),
      body: ListView.builder(
        itemCount:locations.length,
        itemBuilder: (context,index) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 10.0,horizontal:10.0 ),
            child: Card(
              child: ListTile(
                onTap: () {
                  updateTime(index,context);

                },
                title: Text(locations[index].location),
                leading: CircleAvatar(
                  backgroundImage: AssetImage('assets/Flag_of_${locations[index].flag}'),
                ),
              ),
            ),
          );
        }
      ),

    );
  }
}


home.dart


import 'package:flutter/material.dart';
import 'package:universal_time_app/services/universal_time.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  Map data={};

  @override
  Widget build(BuildContext context) {

    data=data.isEmpty ? data: ModalRoute.of(context)?.settings.arguments as Map;
    print(data);
    print('hi');

    String? bgImage='Nw1.jpg';

    //set bg image
    if (data['isdaytime'] == 1) {
      bgImage = 'Dw.jpg';
    }
    //print(bgImage);

    //String bgImage=data['isdaytime']?'Dw.jpg':'Nw1.jpg';
    return
       Scaffold(
         //backgroundColor: Colors.lightBlueAccent[100],x 
         body:Container(
           decoration: BoxDecoration(
             image: DecorationImage(
               image:AssetImage('assets/$bgImage'),
                   fit: BoxFit.cover,

             ),
           ),
           child: SafeArea(
            child:Column(
              children:<Widget>[
                TextButton.icon(
                    onPressed:() async {
                     dynamic result = await Navigator.pushNamed(context, '/location');

                     setState(() {
                       data ={
                         'time' : result['time'],
                         'location' : result['location'],
                         'isdatime':result['isdaytime'],
                         'flag': result['flag'],

                       };
                     });

                     },
                    icon:Icon(Icons.edit_location_rounded,size:45.0,color: Colors.orange,),
                  label: Text(
                      'Edit Location',
                    style: TextStyle(
                      fontSize: 25.0,
                      color: Colors.white,
                    ),
                  ),

                ),
                SizedBox(height: 230.0,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      data['location'],
                      style: TextStyle(
                        color: Colors.yellowAccent,
                        fontSize: 50.0,
                        letterSpacing: 2.0,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.0,),
                Text(
                  data['time'],
                  style: TextStyle(

                    color: Colors.white,
                    fontSize: 70.0,
                    letterSpacing: 2.0,
                  ),
                ),
              ],
            ),
        ),
         ),
      );
  }
}

loading.dart


import 'package:flutter/material.dart';
import 'package:universal_time_app/services/universal_time.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);
  @override
  _LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupWorldTime () async {
  UniversalTime instance=UniversalTime(location: 'Berlin',time: '', flag: 'Germany.png', url:'Europe/berlin',isdaytime:0);
     await instance.getTime();
     Navigator.pushReplacementNamed(context, '/home',arguments: {
       'location':instance.location, 'flag':instance.flag,'time':instance.time,'isdaytime':instance.isdaytime,
     });
}

@override
void initState(){
    super.initState();
    setupWorldTime();
}
@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.greenAccent,
      body:Center(
        child: SpinKitPouringHourGlassRefined(
          color: Colors.white,
          size: 100.0,
        ),
      ),
    );
  }
}


universal_time.dart

import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';

class UniversalTime {

  String location;
  String time;
  String flag;
  String url;
  int isdaytime;

  UniversalTime({
    required this.time,required this.isdaytime,
    required this.location,required this.flag,required this.url});

  Future <void> getTime() async {

//make request
    Response response = await get(Uri.parse('http://worldtimeapi.org/api/timezone/$url'));
    Map data = jsonDecode(response.body);
    String datetime = data['datetime'];
    String offset1 = data['utc_offset'].substring(1,3);
    String offset2 = data['utc_offset'].substring(4,6);

    DateTime now = DateTime.parse(datetime);
    now = now.add(Duration(hours: int.parse(offset1), minutes: int.parse(offset2)));

    isdaytime=now.hour > 5 && now.hour < 20 ? 1:0;
    print(isdaytime);
    //print('aakash');
    //Set the time property
    time=DateFormat.jm().format(now);
    //print(time);
  }

}


CodePudding user response:

I could be wrong, as this is a complex app and I can't exactly run it right now, however the error code that you got indicates that it got a null value when attempting to read a value on line 75 on home.dart (I know this because #0 on your stack was home.dart and it shows the line number)

this is line 75: data['location'] this tells me that data does not have a location key, as I said, I could be wrong, and hopefully print(data) on line 19 should be able to disprove this theory. So before doing anything else, I would check to see what that print statement says. Anyway, here is my guess as to why this is happening to you.

data=data.isEmpty ? data: ModalRoute.of(context)?.settings.arguments as Map;

this line says: if data is empty, data should be equal to data, else, data should be equal to ModalRoute..., I'd bet you got it backwards, it should be:

data=data.isEmpty ? ModalRoute.of(context)?.settings.arguments as Map: data;

I also think its possible that home is being sent with no arguments as an initial route, but you would know that better than I.

CodePudding user response:

The error message is an indication that somewhere in the code, you have assigned null to a var that requires a non-nullable String. Based on the code provided above, my best guess would be the result of your navigator in home.dart for the result['location'] or result['time'] is returning null

  • Related