Home > front end >  Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null
Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null

Time:01-18

I am totally new to flutter and followed a course and got this far. I am not really sure how to fix the problem.

Expected a value of type 'Map<dynamic, dynamic>', but got one of type 'Null'

Here's the code:

import 'package:flutter/material.dart';

class Homepage extends StatefulWidget {
  const Homepage({Key? key}) : super(key: key);

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

class _HomepageState extends State<Homepage> {
  Map data = {};
  @override
  Widget build(BuildContext context) {
    data = data.isNotEmpty
        ? data
        : ModalRoute.of(context)!.settings.arguments
            as Map; //Here's where the error occurs...

    String bgi = data['isDaytime'] ? 'day.jpg' : 'night.jpg';

    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          dynamic result = await Navigator.pushNamed(context, '/location');
          setState(() {
            if (result != null) {
              data = {
                'time': result['time'],
                'location': result['location'],
                'isDaytime': result['isDaytime'],
                'flag': result['flag']
              };
            }
          });
        },
        materialTapTargetSize: MaterialTapTargetSize.padded,
        elevation: 0,
        backgroundColor: Colors.transparent,
        child: Icon(Icons.gps_fixed_sharp,
            size: 30, color: const Color.fromRGBO(47, 145, 182, 1)),
      ),

[Edited]

This is my arguments:

class _LoadingState extends State<Loading> {
  void setupWorldTime() async {
    WorldTime instance = WorldTime(
      location: 'London',
      flag: 'uk.png',
      url: 'Europe/London',
    );
    await instance.getTime();
    Navigator.pushReplacementNamed(context, '/homepage', arguments: {
      'location': instance.location,
      'flag': instance.flag,
      'time1': 0.toString()   instance.time.substring(0, 1),
      'time2': instance.time.substring(2, 5),
      'isDaytime': instance.isDaytime,
    });
  }

Kindly help me with the solution.

CodePudding user response:

It could be because of the argument is empty or null. Try to assign the variable to nullable map (Map?). So your code will be like this:

    Map? data = {};
  @override
  Widget build(BuildContext context) {
    data = (data?.isNotEmpty ?? false) ? data : ModalRoute.of(context)!.settings.arguments as Map?; 
  •  Tags:  
  • Related