'new to flutter and dart, creating a beginners project by creating a world time app but this happens when i run the code

here are how my files are arranged lib -> services,screens,main.dart. services->worldtime.dart. screen -> choose_location.dart,loading.dart,home_screen.dart. and HERE IS THE ERROR.

type 'Null' is not a subtype of type 'Map<dynamic, dynamic>' in type cast and also type 'Null' is not a subtype of type 'bool'.

the problem is the code where written in old flutter version and i need to know how to change to the new version

so this is the code for my home_screen.dart file.

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

class WorldTime{
  String location;
  String? time = "";
  String url;
  String flag;
  bool isdaytime = true;

  WorldTime({required this.location,required this.url,required this.flag});

  Future<void> getTime ()async{
    try{
      Response response =  await get(Uri.parse('http://worldtimeapi.org/api/timezone/$url'));
      Map data = jsonDecode(response.body);
      //print(data);
      String datetime = data["datetime"];
      String offset = data["utc_offset"].substring(1,3);
      //print(datetime);
      print(offset);
      DateTime now  = DateTime.parse(datetime);
      now = now.add(Duration(hours: int.parse(offset)));
      //seting data and time property;
      isdaytime = now.hour > 6 && now.hour >7 ? true:false;
      time = DateFormat.jm().format(now);
    }catch (e){
      print("caught error: $e");
      time = "couldn't get time data ";
    }




  }

}

here is the loadingscreen.dart code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.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
  void initState() {
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    data = data.isNotEmpty
        ?data
        :ModalRoute.of(context)!.settings.arguments as Map;
    print(data);
    String BigImage = data['isDayTime'] ?  'day.jpg' : 'night.jpg';
    Color? bigColor = data['isDayTime'] ? Colors.blue : Colors.black;

    return Scaffold(
      backgroundColor: bigColor,
      body: SafeArea(
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("images/$BigImage"),
              fit: BoxFit.cover
            )

          ),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0,120,0,0),
            child: Column(
              children: [
                TextButton.icon(onPressed:  () async{
                  dynamic result = Navigator.pushNamed(context, "/location");
                  setState(() {
                    data = {
                      "time": result["time"],
                      "location": result["location"],
                      "isdaytime": result["isdaytime"],
                      "flag": result["flags"]
                    };

                  });
                },
                    icon:Icon(Icons.edit_location,
                    color: Colors.yellow,),
                    label: Text("set location.")),
                SizedBox(height:20),
                Row(mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      data["location"],
                      style: TextStyle(
                        fontSize: 35,
                        letterSpacing: 3,
                      ),
                    )
                  ],
               ),
                SizedBox(height: 20,),
                Text(data["time"],
                style: TextStyle(
                  fontSize: 66
                ),
                    )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

thanks in advance



Solution 1:[1]

I don't think doing

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

is the way to call your method. Instead try:

data = data.isNotEmpty
        ? data
        : await WorldTime(/*pass needed data here*/).getTime();

NB: You can't use await in build() just like that (outside of an async method), so think about that too.

And if you are using newer versions of Dart & Flutter (with null-safe), and you are not sure your response will always be not-null, try to check with:

data.containsKey('key') // replace key with your key

before using your Map.

Also, if you just want to call the method once, I would advise to rather call it inside initState() than build().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fsbelinda