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

Issue

i am learning responsive web but i am stuck here in some kind of error like

Expected a value of type ‘Widget’, but got one of type ‘Null’

don’t know how to fix this error i tried a lot but i think i can’t solve this without someone’s help.

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

Solution

largeScreen, mediumScreen and smallScreen all have the type Widget?, meaning: "either a Widget or null.

When you return largeScreen as Widget, if largeScreen is null, you will get an error, because null is not a valid value for Widget (just like 123 as String would throw, since the types are not assignable).

Looking at your code, if all 3 of those variables are null, you’d eventually try to return null from the LayoutBuilder parameter, which is always an error, because it returns a non-null Widget.

Make sure you account for the case where all of these are null, or make sure they are never all null at the same time (perhaps with an assert statement).

Answered By – cameron1024

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *