应为 'Widget' 类型的值,但得到了 'Null' 类型的值

Expected a value of type 'Widget', but got one of type 'Null'

我正在学习响应式网络,但我被困在某种错误中,例如

Expected a value of type 'Widget', but got one of type 'Null'

不知道如何解决这个错误我尝试了很多,但我认为没有别人的帮助我无法解决这个问题。

import 'package:flutter/material.dart';

const int largeScreenSize = 1366;
const int mediumScreenSize = 768;
const int smallScreenSize = 360;
const int customScreenSize = 1100;

class Responsiveness extends StatelessWidget {
   final Widget? largeScreen;
   final Widget? mediumScreen;
   final Widget? smallScreen;

   const Responsiveness({
    this.largeScreen,
    this.mediumScreen,
    this.smallScreen,
  });

   @override
   Widget build(BuildContext context) {
     return LayoutBuilder(builder: (context, constraints) {
       double _width = constraints.maxWidth;
        if (_width >= largeScreenSize) {
         return largeScreen as Widget;
       } else if (_width >= mediumScreenSize && _width < largeScreenSize) {
         return mediumScreen ?? largeScreen as Widget;
       } else {
         return smallScreen ?? largeScreen as Widget;
       }
     });
   }
 }

largeScreenmediumScreensmallScreen 都具有类型 Widget?,意思是:“Widgetnull

当你 return largeScreen as Widget 时,如果 largeScreen 为空,你会得到一个错误,因为 null 不是 Widget 的有效值(就像 123 as String 会抛出,因为类型不可分配)。

查看您的代码,如果所有 3 个变量都是 null,您最终会尝试 return null 来自 LayoutBuilder 参数,即总是一个错误,因为它 return 是一个非空 Widget.

确保考虑到所有这些都是 null 的情况,或者确保它们绝不会同时全部为空(也许使用 assert 语句)。