0

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

3
  • Coul you provide the whole stacktrace please ?
    – FDuhen
    Jan 30, 2022 at 20:54
  • how do i do that Jan 30, 2022 at 21:23
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Jan 31, 2022 at 8:30

1 Answer 1

1

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;
7
  • Thank you sir I commented the ternary operators.. that was the problem but now I'm gettin the error.. LateInitialisationEroor : Local variable 'bgImage' has not been initialised. If I put it as null the if statement won't work Jan 30, 2022 at 21:13
  • You can initiialize it with a default value String bgImage = ''
    – esentis
    Jan 30, 2022 at 21:17
  • did that and the if statement doesnt work at all and the compiler says failed to load assests.... and could you suggest someone on youtube where i can learn flutter if not YouTube any platform Jan 30, 2022 at 21:19
  • It is not effecting the if statements but your build method. Try instead of empty string, giving a default asset value e.g String bgImage = 'day.jpg'
    – esentis
    Jan 30, 2022 at 21:22
  • now it just shows the day.jpg image Jan 30, 2022 at 21:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.