kartik
kartik

Reputation: 191

Is it possible to make user select either of the named arguments in flutter?

I want to let the user of widget know that either one of the argument needs to passed values to so that it can't throw null error.

import 'package:flutter/material.dart';

class TestWidget extends StatelessWidget {
  const TestWidget({
    super.key,
    this.leadingString,
    this.leadingIcon,
  });

  final String? leadingString;
  final Widget? leadingIcon;
  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: leadingIcon ?? Text(leadingString!),
    );
  }
}

Upvotes: 0

Views: 42

Answers (1)

Peter Koltai
Peter Koltai

Reputation: 9734

You can use assert at the constructor to specify a condition like that. If the widget is constructed in a way that the assertion fails it will throw an "assertion failed" error:

const TestWidget({
  super.key,  
  this.leadingString,
  this.leadingIcon,
}) : assert (leadingString != null || leadingIcon != null,
         'either leadingString or leadingIcon must be provided');

Upvotes: 1

Related Questions