dart 应为“Map< dynamic,dynamic>”类型的值,但得到的是“Null”类型的值

fkaflof6  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(145)

我是一个完全新的Flutter和遵循的课程,并得到了这一点。我真的不知道如何解决这个问题。
应为“Map<dynamic,dynamic>”类型的值,但得到的是“Null”类型的值
代码如下:

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)),
      ),

[编辑]
这是我的论点:

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,
    });
  }

请帮我解决这个问题。

z4iuyo4d

z4iuyo4d1#

这可能是因为参数为空或null。尝试将变量赋给可空map(Map?)。因此,您的代码将如下所示:

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

相关问题