11

in Flutter framework i'm trying to set default value for parameters as borderRadius, in this sample how can i implementing that? i get Default values of an optional parameter must be constant error when i try to set that, for example:

class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
  }):this.borderRadius = BorderRadius.circular(30.0);
}


class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius= BorderRadius.circular(30.0);
  SimpleRoundButton({
    this.borderRadius,
  });
}


class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
    this.borderRadius=  BorderRadius.circular(30.0)
  });
}

all of this samples are incorect

DolDurma
  • 15,753
  • 51
  • 198
  • 377

3 Answers3

16

BorderRadius.circular() is not a const function so you cannot use it as a default value.

To be able to set the const circular border you can use BorderRadius.all function which is const like below:

class SimpleRoundButton extends StatelessWidget {
  final BorderRadius borderRadius;
  SimpleRoundButton({
    this.borderRadius: const BorderRadius.all(Radius.circular(30.0))
  });

  @override
  Widget build(BuildContext context) {
    return null;
  }
}
Gunhan
  • 6,807
  • 3
  • 43
  • 37
12

Gunhan's answer explained how you can set a default BorderRadius.

In general, if there isn't a const constructor available for the argument type, you instead can resort to using a null default value (or some other appropriate sentinel value) and then setting the desired value later:

class Foo {
  Bar bar;

  Foo({Bar? bar}) : bar = bar ?? Bar();
}

Note that explicitly passing null as an argument will do something different with this approach than if you had set the default value directly. That is, Foo(bar: null) with this approach will initialize the member variable bar to Bar(), whereas with a normal default value it would be initialized to null and require that the member be nullable. (In some cases, however, this approach's behavior might be more desirable.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0
    import 'package:flutter/material.dart';

class MyStatelessWidget extends StatelessWidget {
  // Declare a parameter with a default value using curly braces
  final String message;

  // Constructor with the default value provided for the parameter
  MyStatelessWidget({this.message = 'Hello, World!'});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Stateless Widget Example')),
      body: Center(
        child: Text(message),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyStatelessWidget(),
  ));
}

for more details you can refer : https://flutterwebbies.com/flutter/tutorial/how-to-set-default-value-for-parameter/

vishnu reji
  • 193
  • 2
  • 11