Home > Mobile >  How to work with nullable widgets in flutter?
How to work with nullable widgets in flutter?

Time:10-18

I want to make my screens responsive. Therefor I wrote this ResponsiveWidget:

import 'package:flutter/material.dart';

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

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

  const ResponsiveWidget(
      {Key? key,
        required this.largeScreen,
         this.mediumScreen,
         this.smallScreen})
      : super(key: key);

static bool isSmallScreen(BuildContext context)=>
    MediaQuery.of(context).size.width<smallScreenSize;

static bool isMediumScreen(BuildContext context)=>
    MediaQuery.of(context).size.width>=mediumScreenSize &&
    MediaQuery.of(context).size.width<largeScreenSize;

static bool isLargeScreen(BuildContext context)=>
    MediaQuery.of(context).size.width>=largeScreenSize;

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

    );
  }
}

...now I got an error for "return mediumScreen" and "return smallScreen" (because they can be null)

The return type 'Widget?' isn't a 'Widget', as required by the closure's context.

How to add a default return value for this widget, so I can use some screens as optional parameters?

CodePudding user response:

Solved this with

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

    );
  }
  • Related