skip to Main Content

TextStyle.merge and TextStyle.copyWith have different description but I seem to get the same result.
If merge behaves same as copyWith,then there is no need for adding the method merge to TextStyle.Are there any differences between them?


class TestView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    const baseStyle = TextStyle(color: Colors.blue, fontSize: 16);
    final titleStyle = baseStyle.copyWith(
      color: Colors.red,
      decoration: TextDecoration.lineThrough,
    ); // copyWith
    final noticeStyle = baseStyle.merge(const TextStyle(
      color: Colors.grey,
      decoration: TextDecoration.lineThrough,
    )); // merge
    return Column(
      children: [
        Text('this is title style', style: titleStyle),
        Text('this is notice style', style: noticeStyle),
      ],
    );
  }
}

2

Answers


  1. merge eventually call copyWith, so if other != null && other.inherit, they are no difference

    enter image description here

    Login or Signup to reply.
  2. The different is the param you pass into it

    If you already have an exist TextStyle then use merge:

    final yourStyle = TextStyle().merge(existBaseTextStyle);
    

    If you only need to change some properties, use copyWith():

    final yourStyle = TextStyle().copyWith(color: Colors.red);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search