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
                        )
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }
    
    }
3
  • 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<void> getTime() async { // make the request Commented Mar 4, 2022 at 10:28
  • Future<void> getTime() async { try { Response response = await get( Uri.parse('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'; Commented Mar 4, 2022 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 Commented Aug 4, 2022 at 19:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

9 Comments

thanks but This error has appeared After I followed your instructions "Null check operator used on a null value "what is the problem?
Can you share that line of code where it throwing "Null check operator used on a null value"?
======== 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
This issue is in main.dart file, line no 12, Can you share main.dart file code?
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(), } ));
|
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']
                        };
                      });

4 Comments

thanks but This error has appeared After I followed your instructions " type 'Null' is not a subtype of type 'String' "what is the problem?
data = { 'Time': result['Time'] ?? '', 'Location': result['Location'] ?? '', 'isDayTime': result['isDayTime'] ?? false, 'Flag': result['Flag'] ?? '', };
@M Karimi the same error still appear
This error appear, because in somewhere a String variable, get null value. You should check your variables and by helping ?? '' operator, resolve the error.
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

1 Comment

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<dynamic, dynamic>?' can't be assigned to a variable of type 'Map<dynamic, dynamic>' because 'Map<dynamic, dynamic>?' is nullable and 'Map<dynamic, dynamic>' isn't.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.