Home > Software design >  Does keyword late work as I expect when constructing Widgets
Does keyword late work as I expect when constructing Widgets

Time:07-13

I have a convenience StatelessWidget that returns the appropriate widget for one of three display size breakpoints:

/// Return the most appropriate widget for the current display size.
/// 
/// If a widget for current display size is not available, chose the closest smaller variant.
/// A [mobile] size widget is required.
class SizeAppropriate extends StatelessWidget {
  // ignore: prefer_const_constructors_in_immutables
  SizeAppropriate(
    this.context,
    {
      required this.mobile,
      this.tablet,
      this.desktop,

      Key? key
    }
  ) : super(key: key);

  final BuildContext context;
  late final Widget mobile;
  late final Widget? tablet;
  late final Widget? desktop;

  @override
  Widget build(BuildContext context) {
    switch (getDisplaySize(context)) {
      case DisplaySize.mobile:
        return mobile;
      case DisplaySize.tablet:
        return tablet ?? mobile;
      case DisplaySize.desktop:
        return desktop ?? tablet ?? mobile;
    }
  }
}

I then use it like this:

SizeAppropriate(
    context,
    mobile: const Text('mobile'),
    desktop: const Text('desktop'),
)

Is the keyword late working here as intended, building only the correct variant, or am I hogging the performance, because all variants are constructed (or am I even creating an anti-pattern)?

Should I use builder functions instead?

Edit:

This answer makes me think I'm correct. Although the last two sentences make me think I'm not correct.

When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed.

When I do log('mobile') and log('desktop') in the respective widgets being constructed, I only get one type of message in the console.

Edit 2 – minimum working example:

This is my main.dart in a newly generated project (VS Code command >Flutter: New Project – Application). It might be worth noting, that I am testing this on Linux.

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: SizeAppropriate(
          context,
          mobile: const Mobile(),
          tablet: const Tablet(),
          desktop: const Desktop(),
        ),
      ),
    );
  }
}

class Mobile extends StatelessWidget {
  const Mobile({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    log('mobile');
    return const Text('mobile');
  }
}

class Tablet extends StatelessWidget {
  const Tablet({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    log('tablet');
    return const Text('tablet');
  }
}

class Desktop extends StatelessWidget {
  const Desktop({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    log('desktop');
    return const Text('desktop');
  }
}

enum DisplaySize {
  desktop,
  tablet,
  mobile,
}

DisplaySize getDisplaySize(BuildContext context) {
  Size size = MediaQuery.of(context).size;
  if (size.width < 768) {
    return DisplaySize.mobile;
  }
  else if (size.width < 1200) {
    return DisplaySize.tablet;
  }
  else {
    return DisplaySize.desktop;
  }
}

class SizeAppropriate extends StatelessWidget {
  // ignore: prefer_const_constructors_in_immutables
  SizeAppropriate(
    this.context,
    {
      required this.mobile,
      this.tablet,
      this.desktop,

      Key? key
    }
  ) : super(key: key);

  final BuildContext context;
  late final Widget mobile;
  late final Widget? tablet;
  late final Widget? desktop;

  @override
  Widget build(BuildContext context) {
    switch (getDisplaySize(context)) {
      case DisplaySize.mobile:
        return mobile;
      case DisplaySize.tablet:
        return tablet ?? mobile;
      case DisplaySize.desktop:
        return desktop ?? tablet ?? mobile;
    }
  }
}

CodePudding user response:

late does not do what you want. It's only for the null-safety feature and when you do or don't get warnings about it. Those two texts get built every time regardless of environment, because they need to be there when they are passed to your widget.

If you to only build the appropriate widgets for each size when the size is known, you indeed need indeed pass two builders, one of which you call if appropriate.


For two constant Text widgets, that would be too much overhead, but I am assuming you want "heavier" widget trees for both options in the end.

  • Related