0

I am creating a multi-paged app on flutter to To determine the time based on the location, but when the code is turned on, there's a problem on this page, I tried to fix the problem, but the error still exists" type 'Null' is not a subtype of type 'bool'" I'll include the other pages in the comments.

 import 'package:flutter/material.dart';
    class Home extends StatefulWidget {
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
       Map? data={};
      @override
    
      Widget build(BuildContext context) {
    
    
           if (data!= null) {
            data = ModalRoute.of(context)!.settings.arguments as Map?;}
    
        // set background image
        final  String? bgImage = data?['isDayTime'] ? 'day.png' : 'night.png';
        final Color? bgColor =  data?['isDayTime'] ? Colors.blue : Colors.indigo[700];
    
         return Scaffold(
           backgroundColor: bgColor,
           body: SafeArea(
            child: Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('asset/$bgImage'),
                    fit: BoxFit.cover,
                  )
              ),
              child: Padding(
                padding: const EdgeInsets.fromLTRB(0, 120.0, 0, 0),
                child: Column(
                  children: <Widget>[
                    FlatButton.icon(
                      onPressed: () async {
                        dynamic result = await Navigator.pushNamed(context, '/location');
                        if(result != null){
                          setState(() {
                            data = {
                              'Time': result['Time'],
                              'Location': result['Location'],
                              'isDayTime': result['isDayTime'],
                              'Flag': result['Flag']
                            };
                          });
                        }
                      },
                      icon: Icon(
                        Icons.edit_location,
                        color: Colors.grey[300],
                      ),
                      label: Text(
                        'Edit Location',
                        style: TextStyle(
                          color: Colors.grey[300],
                        ),
                      ),
                    ),
                    SizedBox(height: 20.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          data?['Location'],
                          style: TextStyle(
                            fontSize: 28.0,
                            letterSpacing: 2.0,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 20.0),
                    Text(
                        data?['Time'],
                        style: TextStyle(
                            fontSize: 66.0,
                            color: Colors.white
                        )
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    
    }
  • class WorldTime{ String Location ; late String Time; String Flag ; String Url ; late bool isDayTime; WorldTime({ required this.Location, required this.Flag,required this.Url}); Future getTime() async { // make the request – Esraa Ibrahim Mar 04 '22 at 10:28
  • Future getTime() async { try { Response response = await get( Uri.parse('http://worldtimeapi.org/api/timezone/$Url')); Map data = jsonDecode(response.body); String datetime = data['datetime']; String offset = data['utc_offset'].substring(0, 3); 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(e); Time = 'could not get time'; – Esraa Ibrahim Mar 04 '22 at 10:46
  • Does this answer your question? [Type Null is not a subtype of type int error when tried fetch data from an API](https://stackoverflow.com/questions/67917585/type-null-is-not-a-subtype-of-type-int-error-when-tried-fetch-data-from-an-api) – TylerH Aug 04 '22 at 19:34

3 Answers3

1

Your data is of type Map, and if the data does not have isDayTime field than it is returning null and, ternary operator decision can not be made on null.
So, to fix this either you can check whether your data map have the filed using data.containsKey('isDayTime') or You can use ?? (null aware operator) to assign a fallback value, so that your ternary operator will always have boolean value.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • thanks but This error has appeared After I followed your instructions "Null check operator used on a null value "what is the problem? – Esraa Ibrahim Mar 05 '22 at 09:56
  • Can you share that line of code where it throwing "Null check operator used on a null value"? – Abhishek Thakur Mar 05 '22 at 12:40
  • ======== Exception caught by widgets library ======================================================= The following _CastError was thrown building Home(dirty, dependencies: [_ModalScopeStatus], state: _HomeState#407e3): Null check operator used on a null value The relevant error-causing widget was: Home Home:file:///C:/Users/96278/Desktop/worldtime/lib/main.dart:12:29 – Esraa Ibrahim Mar 05 '22 at 18:00
  • This issue is in main.dart file, line no 12, Can you share main.dart file code? – Abhishek Thakur Mar 07 '22 at 05:08
  • import 'package:flutter/material.dart'; import 'package:worldtime/pages/home.dart'; import 'package:worldtime/pages/loading.dart'; import 'package:worldtime/pages/location.dart'; void main() => runApp(MaterialApp( initialRoute: '/home', routes: { '/': (context) => Loading(), '/home': (context) => Home(), '/location': (context) => Location(), } )); – Esraa Ibrahim Mar 07 '22 at 23:51
  • I don't see any issue in main.dart file. – Abhishek Thakur Mar 08 '22 at 05:11
  • In Home's state you have created data variable and you have assigned it with empty map, so it will be never null. your initial route is /home that means it is loading Home widget. but at initial route you can not pass any arguments, so ModalRoute.of(context)!.settings.arguments as Map?; is having null value. ModalRoute.of(context)!.settings.arguments as Map?; will have value if you navigate with arguments like Navigator.pushNamed(context,'/home',arguments:{}); than in the landing page you can use ModalRoute.of(context)!.settings.arguments as Map?; to get the passed arguments. – Abhishek Thakur Mar 08 '22 at 05:29
  • https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments. – Abhishek Thakur Mar 08 '22 at 05:29
  • Use FutureBuilder/StreamBuilder based on your need. – Abhishek Thakur Mar 08 '22 at 05:31
0

1- data?['isDayTime'] to (data?['isDayTime']?? false)

2- I think the wrong in variable (isDayTime) so you shouldn't use (late) key so if you are sure 100% you will declare this variable so remove late and change it to final if it is't changing again

3- convert this Map? data={}; to Map data={}; because this is already declared and look at this link https://dart.dev/null-safety/understanding-null-safety

Mahmoud Salah Eldin
  • 1,739
  • 16
  • 21
  • thanks first of all 1 - I modified it 2- late using for null safety so I have to give the (isDayTime) initial value (EX: false) or use late .3 when I remove the? this appears ( Error: A value of type 'Map?' can't be assigned to a variable of type 'Map' because 'Map?' is nullable and 'Map' isn't.) – Esraa Ibrahim Mar 05 '22 at 10:46
0

Instead of

        final  String? bgImage = data?['isDayTime'] ? 'day.png' : 'night.png';
    final Color? bgColor =  data?['isDayTime'] ? Colors.blue : Colors.indigo[700];

write

        final  String? bgImage = (data?['isDayTime'] ?? false) ? 'day.png' : 'night.png';
    final Color? bgColor =  (data?['isDayTime'] ?? false) ? Colors.blue : Colors.indigo[700];

and also instead of

setState(() {
                        data = {
                          'Time': result['Time'],
                          'Location': result['Location'],
                          'isDayTime': result['isDayTime'],
                          'Flag': result['Flag']
                        };
                      });

write

setState(() {
                        data = {
                          'Time': result['Time'],
                          'Location': result['Location'],
                          'isDayTime': result['isDayTime'] ?? false,
                          'Flag': result['Flag']
                        };
                      });
M Karimi
  • 1,991
  • 1
  • 17
  • 34
  • thanks but This error has appeared After I followed your instructions " type 'Null' is not a subtype of type 'String' "what is the problem? – Esraa Ibrahim Mar 05 '22 at 10:03
  • data = { 'Time': result['Time'] ?? '', 'Location': result['Location'] ?? '', 'isDayTime': result['isDayTime'] ?? false, 'Flag': result['Flag'] ?? '', }; – M Karimi Mar 05 '22 at 14:55
  • @M Karimi the same error still appear – Esraa Ibrahim Mar 05 '22 at 18:03
  • This error appear, because in somewhere a String variable, get null value. You should check your variables and by helping ?? '' operator, resolve the error. – M Karimi Mar 06 '22 at 03:09