Skip to content

Instantly share code, notes, and snippets.

@dkbast
Created March 5, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkbast/e8cbb1746dc0676a43b78ec03204b4c4 to your computer and use it in GitHub Desktop.
Save dkbast/e8cbb1746dc0676a43b78ec03204b4c4 to your computer and use it in GitHub Desktop.
Optional Widgets with nullable parameter
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Optional Widgets with nullable parameter',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Optional Widgets with nullable parameter'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String thisStringIsNull;
String thisStringIsNotNull = 'text';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// We often check if a parameter is not null and then pass the parameter to a widget to be built like this
if (thisStringIsNull != null) Text(thisStringIsNull),
if (thisStringIsNotNull != null) Text(thisStringIsNotNull),
// if we had a way to return void instead of null the widget could just handle the null check internally.
// simply returning null is not an option, but the null aware
// spread operator ...? allows for something like this:
...?nullableText(thisStringIsNotNull),
...?nullableText(thisStringIsNull),
// I would prefer to have an operator which works at the parameter level
// like this: Text(?parameterCouldBeNull) - where the constructor is only called if 'parameterCouldBeNull != null'
],
),
),
);
}
}
List<Widget> nullableText(String text) {
if (text == null) {
return null;
} else {
return [Text(text)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment