type 'String' is not a subtype of type 'bool' flutter

Issue

The following _TypeError was thrown building Home(dirty, dependencies: [_ModalScopeStatus], state: _HomeState#f1f65):
type ‘String’ is not a subtype of type ‘bool’

this is the error

import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
class WorldTime{

  late String location;// location name from UI
  String time = '';// the time in that location
  late String flag;//url to flag icon
  late String url;// location part of url API
  late String isDaytime = '';// daytime or not

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

  Future<void> getTime() async {
    try {
      Response response = await http.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 offseth = data['utc_offset'].substring(0, 3);
      String offsetm = data['utc_offset'].substring(4, 6);
      // print(datetime);
      //print(offsetm);

      //create a date time object
      DateTime now = DateTime.parse(datetime);
      now = now.add(
          Duration(hours: int.parse(offseth), minutes: int.parse(offsetm)));

      //set time
      if(now.hour > 6 && now.hour < 12)
        {
          isDaytime ='1';
        }
      else if(now.hour >=12 && now.hour < 4 )
        {
          isDaytime = '2';
        }
      else if(now.hour >=4 && now.hour < 7 )
      {
        isDaytime = '3';
      }
      else if(now.hour >=7)
      {
        isDaytime = '4';
      }
      time = DateFormat.jm().format(now);
    }
    catch (e) {
      print('caught error:$e');
      time = 'could not get time';
    }
  }
}

this is the class (above)

import 'package:flutter/material.dart';
import 'package:world_time/services/world_time.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
class Loading extends StatefulWidget {
  const Loading({Key? key}) : super(key: key);

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

class _LoadingState extends State<Loading> {
  @override



  void setupWorldTime() async
  {
    WorldTime instance = WorldTime(location: 'Kolkata', flag: 'India.png', url: 'Asia/Kolkata');
    await instance.getTime();
  // print(instance.time);

      Navigator.pushReplacementNamed(context, '/home', arguments: {
        'location': instance.location,
        'flag': instance.flag,
        'time': instance.time,
        'daytime': instance.isDaytime,
      });
  }
  @override
  void initState() {
    super.initState();
    setupWorldTime();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      body: Center(
        child:  LoadingAnimationWidget.staggeredDotsWave(
          color: Colors.white,
          size: 100,
        ),
        ),
    );
  }
}

this is the code for loading

import 'package:flutter/material.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 = ModalRoute.of(context)!.settings.arguments as Map;
   // print(data['daytime']);
    //set backround
    late String bgImage;
    if(data['daytime'] == '1')
      {
        bgImage = 'day.jpg';
      }
    else if(data['daytime'] == '2')
    {
      bgImage = 'noon.jpg';
    }
    else if(data['daytime'] == '3')
    {
      bgImage = 'eve.jpg';
    }
    else if(data['daytime'] == '4')
    {
      bgImage = 'night.jpg';
    }
    Color textColor = data['daytime'] ? Colors.black : Colors.white;
    Color bgColor = data['daytime'] ? Color.fromRGBO(238, 196, 162, 100) : Colors.black;

    return Scaffold(
      backgroundColor: bgColor,
      body:SafeArea(

        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/$bgImage'),
              fit:BoxFit.cover,

            ),
          ),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0, 120.0, 0, 0),
            child: Column(
              children: [
                TextButton.icon(
                    onPressed: () {
                      Navigator.pushNamed(context,'/location');
                    },
                    icon: Icon(Icons.edit_location_outlined,
                      color: textColor,
                    ),
                    label: Text('Edit Location',
                      style: TextStyle(
                        color: textColor,
                      ),

                    ),
                    style: TextButton.styleFrom(primary: Colors.white),
                ),
                SizedBox(height: 20.0),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(data['location'],
                    style: TextStyle(
                      fontSize: 28.0,
                      letterSpacing: 2.0,
                      color: textColor,
                    ),
                    )
                  ],
                ),
                SizedBox(height: 20.0),
                Text(data['time'],
                style: TextStyle(
                  fontSize: 66.0,
                  color: textColor,
                ),
                ),

              ],
            ),
          ),
        ),
      ),
    );
  }
}

and this is the code for the home.
Can someone help me out im new to flutter. And can someone suggest any youtube channel to learn flutter

Solution

From what I see, I think the problem is here :

Color textColor = data['daytime'] ? Colors.black : Colors.white;

data['daytime'] is of type String based on your code. Ternary operator accepts a bool value. Maybe you want to do something like this ?

Color textColor = data['daytime'] == '4' ? Colors.black : Colors.white;

Answered By – esentis

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.