首页 > 解决方案 > 使用 {} 表示法分配 Flutter 路由时出错

问题描述

我正在使用 Dart 进行 The Complete 2020 Flutter Development Bootcamp,这段代码直接来自视频:

import 'package:flutter/material.dart';
import 'screen0.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/', (context) => Screen0(),
      },
    );
  }
}

代码未编译并出现错误The argument type 'Set<Object>' can't be assigned to the parameter type 'Map<String, Widget Function(BuildContext)>'.

如果我投射路线对象,那么它就是

import 'package:flutter/material.dart';
import 'screen0.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/', (context) => Screen0(),
      } as Map<String, WidgetBuilder>,
    );
  }
}

代码编译,但运行时崩溃,出现错误type '_CompactLinkedHashSet<Object>' is not a subtype of type 'Map<String, (BuildContext) => in type cast

这些视频应该是最新的,所以这似乎是最近的变化。谁能告诉我我做错了什么,或者我应该如何解决这个问题?

版本:

Flutter 1.12.13+hotfix.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f139b11009 (5 weeks ago) • 2020-03-30 13:57:30 -0700
Engine • revision af51afceb8
Tools • Dart 2.7.2

标签: flutter

解决方案


问题出在您的route. 您使用逗号,而不是冒号:

这里

'/', (context) => Screen0() //The comma should be a colon.

像这样将逗号替换为冒号...

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => Screen0()
      } as Map<String, WidgetBuilder>,
    );
  }
}

推荐阅读