Flutter: Omit else clause in ternary operator in order to use default styling

Viewed 616

I am often coming across situations where I would like to style a Widget based on some conditional which might look like the following:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: Home()));

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool condition = true;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: OutlinedButton(
            style: OutlinedButton.styleFrom(
                side:
                    BorderSide(color: condition ? Colors.blue : /** DEFAULT Color**/)),
            onPressed: () => _changeColor(),
            child: Text('Press')),
      ),
    );
  }

  void _changeColor() => setState(() => condition = !condition);
}

The above code does not compile as Flutter wants me to specify an alternative color if condition is false. But I do not want to specify any color but simply use the default color set by my Theme in case of condition evaluating to false. How is this possible?

I know that when using the ternary operator in situations where a Widget is to be returned (e.g. after child: condition ? Container() : ...), we can simply specify SizedBox.shrink() in order to have no effect. What would I do respectively when not wanting to specify any style but fall back to default behaviour?

2 Answers

If a property to a constructor to a Flutter widget isn't required, it is generally safe to give it null (as that is the default value for any omitted optional property) at which point that widget will either ignore that property or fall back to an implicit default value, whichever is appropriate.

So in this case, your "default" value for color can simply be null, at which point the constructor for BorderSide will fall back to a default value of Color(0xFF000000).

BorderSide(color: condition ? Colors.blue : null)

In the main file, in MaterialApp, we usually put theme details, where we can also put custom styles if we want to. If we don't put custom theme data, then our app will use default styles.

To get theme value, we need context. We can get any theme value using this.

var primaryColor = Theme.of(context).primaryColor;

Theme.of(context) has every value of theme style, you can get the default value from here.

Like

BorderSide(color: condition ? Colors.blue : Theme.of(context).primaryColor)
Related