How to pre-define propeties in classes Flutter

0

I have created a CardText as a stateless widget and I will use it whenever I would be needing it. But I have a problem. As y'all can see, there are properties that I haven't marked as @required. What I want is these properties have a pre-defined value. Like, suppose the color property, it should be 0xFFFFFFFF until and unless I want somewhere to be as 0xFF000000. But these are final properties that can't be assigned on the basis of ??= method. Yes, I know, marking these properties as @required will require me to define each and every property whenever I call it. But having a pre-defined value will help me a lot to save time and a few lines of code. Well, any expert out there, I don't know how to express the problem, so feel free to change the title. Thank you.

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

class CardText extends StatelessWidget {
  final String data;
  final int color;
  final int fontSize;
  final FontWeight fontWeight;
  const CardText(
    this.data, {
    this.color,
    this.fontSize,
    this.fontWeight,
  });


  @override
  Widget build(BuildContext context) {
    return Text(
      data,
      style: GoogleFonts.openSans(
        textStyle: TextStyle(
          fontSize: fontSize,
          fontWeight: fontWeight,
          color: Color(color),
        ),
      ),
    );
  }
}
flutter
asked on Stack Overflow May 20, 2020 by Raghav Joshi • edited May 20, 2020 by Jasurbek

2 Answers

1

You can use the : colon syntax:

const CardText(
    this.data, {
    this.color,
    this.fontSize,
    this.fontWeight,
  }) : color = 0xFFFFFFFF, data = "data"

The code after the colon will be executed before the code inside the curly brackets. From the linked question

The part after : is called "initializer list. It is a ,-separated list of expressions that can access constructor parameters and can assign to instance fields, even final instance fields. This is handy to initialize final fields with calculated values.

answered on Stack Overflow May 20, 2020 by Just learned it
1

If your arguments are optional then you can give default it right away, like following

const CardText({
    this.data, 
    this.color = 0xFFFFFFFF,
    this.fontSize = 14,
    this.fontWeight,
  })
answered on Stack Overflow May 20, 2020 by Jasurbek • edited May 20, 2020 by Jasurbek

User contributions licensed under CC BY-SA 3.0