MergeSemantics Widget - Flutter Widget Guide By Flutter Agency

MergeSemantics Widget – Flutter Widget Guide By Flutter Agency

Earlier we have been through ExcludeSemantics Widget which is a widget that drops all semantics of it’s descendant so now in this article we will get into MergeSemantics Widget  which is used to merge the semantics of it’s children.

Before reaching to MergeSemantics Widget we first need to understand semantic.

What is Semantic in Flutter?

Semantics  is a widget that annotates the widget tree with a description of the meaning of the widgets.

It is used by accessibility tools, search engines, and other semantic analysis software to determine the meaning of the application.

What is MergeSemantics Widget in Flutter?

MergeSemantics Widget is a widget that merges the semantics of it’s descendants.

It will causes all the semantics of the subtree rooted at this node to be merged into one node in the semantics tree.

For example, if you have a widget with a Text node next to a Checkbox Widget, this could be used to merge the label from the Text node with the “checked” semantic state of the checkbox into a single node that had both the label and the checked state. Otherwise, the label would be presented as a separate feature than the checkbox, and the user would not be able to be sure that they were related.

If multiple nodes in the merged subtree can handle semantic gestures, the first one in tree order will be the one to receive the callbacks.

Default constructor of a MergeSemantic Widget will look like below:

MergeSemantics({
Key key,
Widget child,
})

Properties:

  • Key key: This attribute represents the how one widget should replace another widget in a tree.
  • Widget child: This attribute is used to define the widget below this widget in the tree. This widget can only have one child. To layout multiple children, let this widget’s child be a widget such as Row WidgetColumn Widget, or Stack Widget, which have a children’s property, and then provide the children to that widget.

How to use MergeSemantics Widget in Flutter?

Consider a code snippet as below to understand how MergeSemantics Widget works in a Flutter.

Scaffold(
        body: new Container(
      decoration: new BoxDecoration(color: Colors.blue,),
      child: new Center(
          child: MergeSemantics(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
              Card(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Material(
                      elevation: 24.0,
                      child: Padding(
                        padding: const EdgeInsets.all(20.0),
                        child: Text("Sign Up Here"),
                      ),
                    ),
                    Padding(
                        padding: EdgeInsets.fromLTRB(20, 10.0, 20.0, 20.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            TextField(
                              decoration: InputDecoration(
                                labelText: "Email",
                                hintText: "[email protected]",
                              ),
                              autofocus: true,
                            ),
                            TextField(
                              decoration: InputDecoration(
                                labelText: "Password",
                              ),
                              autofocus: true,
                            ),
                            SizedBox(
                              width: double.infinity,
                              // height: double.infinity,
                              child: new RaisedButton(
                                color: Colors.blue,
                                child: Text(
                                  "Sign In",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontFamily: 'Raleway',
                                    fontSize: 22.0,
                                  ),
                                ),
                                onPressed: () => print('Sign In'),
                              ),
                            )
                          ],
                        )),
                  ],
                ),
              ),
        ],
      ),
            ),
          )),
    ),);

Above code will gives us output like below:

MergerSemantic Widget - Flutter Widget Guide By Flutter Agency

MergeSemantic Widget

General Queries on MergeSemantics Widget

  • Is there a cupertino equivelent of SwitchListTile ?

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      State<StatefulWidget> createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
      bool _isSelected = false;
    
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          home: new SafeArea(
              child: new Material(
                  child: new ListView(
                    children: <Widget>[
                      new CupertinoSwitchListTile(
                        value: _isSelected,
                        onChanged: (value) {
                          print("Value changed to $value");
                          setState(() => _isSelected = value);
                        },
                        activeColor: CupertinoColors.activeGreen
                      )
                    ],
                  ))),
        );
      }
    
    }
    
    class CupertinoSwitchListTile extends StatelessWidget {
      /// This has been shamelessly copied from Material/SwitchListTile.
      /// The applicable license applies.
      const CupertinoSwitchListTile({
        Key key,
        @required this.value,
        @required this.onChanged,
        this.activeColor,
        this.title,
        this.subtitle,
        this.isThreeLine: false,
        this.dense,
        this.secondary,
        this.selected: false,
      })  : assert(value != null),
            assert(isThreeLine != null),
            assert(!isThreeLine || subtitle != null),
            assert(selected != null),
            super(key: key);
    
      /// Whether this switch is checked.
      ///
      /// This property must not be null.
      final bool value;
    
      /// Called when the user toggles the switch on or off.
      ///
      /// The switch passes the new value to the callback but does not actually
      /// change state until the parent widget rebuilds the switch tile with the
      /// new value.
      ///
      /// If null, the switch will be displayed as disabled.
      ///
      /// The callback provided to [onChanged] should update the state of the parent
      /// [StatefulWidget] using the [State.setState] method, so that the parent
      /// gets rebuilt; for example:
      ///
      /// ```dart
      /// new SwitchListTile(
      ///   value: _lights,
      ///   onChanged: (bool newValue) {
      ///     setState(() {
      ///       _lights = newValue;
      ///     });
      ///   },
      ///   title: new Text('Lights'),
      /// )
      /// ```
      final ValueChanged<bool> onChanged;
    
      /// The color to use when this switch is on.
      ///
      /// Defaults to accent color of the current [Theme].
      final Color activeColor;
    
      /// The primary content of the list tile.
      ///
      /// Typically a [Text] widget.
      final Widget title;
    
      /// Additional content displayed below the title.
      ///
      /// Typically a [Text] widget.
      final Widget subtitle;
    
      /// A widget to display on the opposite side of the tile from the switch.
      ///
      /// Typically an [Icon] widget.
      final Widget secondary;
    
      /// Whether this list tile is intended to display three lines of text.
      ///
      /// If false, the list tile is treated as having one line if the subtitle is
      /// null and treated as having two lines if the subtitle is non-null.
      final bool isThreeLine;
    
      /// Whether this list tile is part of a vertically dense list.
      ///
      /// If this property is null then its value is based on [ListTileTheme.dense].
      final bool dense;
    
      /// Whether to render icons and text in the [activeColor].
      ///
      /// No effort is made to automatically coordinate the [selected] state and the
      /// [value] state. To have the list tile appear selected when the switch is
      /// on, pass the same value to both.
      ///
      /// Normally, this property is left to its default value, false.
      final bool selected;
    
      @override
      Widget build(BuildContext context) {
        var color =  activeColor ?? Theme.of(context).accentColor;
        print("Active color: ${color.red} ${color.green} ${color.blue}");
        final Widget control = new CupertinoSwitch(
          value: value,
          onChanged: onChanged,
          activeColor: activeColor ?? CupertinoColors.activeGreen,
        );
        return new MergeSemantics(
          child: ListTileTheme.merge(
            selectedColor: activeColor ?? CupertinoColors.activeGreen,
            child: new ListTile(
              leading: secondary,
              title: title,
              subtitle: subtitle,
              trailing: control,
              isThreeLine: isThreeLine,
              dense: dense,
              enabled: onChanged != null,
              onTap: onChanged != null
                  ? () {
                      onChanged(!value);
                    }
                  : null,
              selected: selected,
            ),
          ),
        );
      }
    }
  • Row RenderFlex overflowed by 76 pixels on the right ?

Below are my code I always got some pixel overflowed on right size. I was playing with Expanded Widget and Flexible Widget as well as mainAxisSize of row and column too.

My code look like below:

Widget productDisplayListView(List<Products> listOfProduct, int index) {
    return Container(
      margin: EdgeInsets.all(7),
      child: Container(
        child: Card(
          elevation: 4,
          child: Container(
            padding: EdgeInsets.all(6),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  height: 110,
                  width: 90,
                  child: Image.network(
                    listOfProduct[index].thumbnail ?? '',
                    fit: BoxFit.cover,
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(5),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.zero,
                            margin: EdgeInsets.zero,
                            height: 20,
                            width: 20,
                            child: Icon(
                              Icons.crop_square,
                              color: Colors.red,
                              size: 18,
                            ),
                          ),
                          Flexible(
                            child: Text(
                              'The overflowing RenderFlex has an orientation of Axis.horizontal.',
                              overflow: TextOverflow.ellipsis,
                              softWrap: true,
                              style: TextStyle(
                                  fontSize: 13,
                                  fontWeight: FontWeight.w600,
                                  color: Theme.of(context).primaryColor),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 5),
                      Text(
                        'The overflowing RenderFlex has an orientation of Axis.horizontal.',
                        maxLines: 1,
                        style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            color: Colors.grey),
                      ),
                      SizedBox(height: 5),
                      Text(
                        '₹${listOfProduct[index].price ?? ''}',
                        style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w700,
                            color: Colors.black),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

Updated Code with Fixed Overflow Error. Have to made quite a change in your Widget Tree.

Widget productDisplayListView() {
return Card(
  elevation: 4,
  child: Container(
    padding: EdgeInsets.all(6),
    child: Row(
      children: <Widget>[
        Container(
          height: 110,
          width: 90,
          child: Image.network(
            'https://placeimg.com/250/250/any',
            fit: BoxFit.cover,
          ),
        ),
        SizedBox(
          width: 5.0,
        ),
        Flexible(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              MergeSemantics(
                child: Row(
                  children: <Widget>[
                    Icon(
                      Icons.crop_square,
                      color: Colors.red,
                      size: 18,
                    ),
                    Flexible(
                      child: Text(
                        'The overflowing RenderFlex has an orientation of Axis.horizontal.',
                        overflow: TextOverflow.ellipsis,
                        softWrap: true,
                        style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                            color: Theme.of(context).primaryColor),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 5),
              Text(
                'The overflowing RenderFlex has an orientation of Axis.horizontal.',
                maxLines: 1,
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey),
              ),
              SizedBox(height: 5),
              Text(
                '₹ 10,000',
                style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w700,
                    color: Colors.black),
              )
            ],
          ),
        )
      ],
    ),
  ),
);
}

We will get output like below:

MergeSemantics Widget - Flutter Widget Guide By Flutter Agency

MergeSemantics Widget

Key Note :

Be aware that if two nodes in the subtree have conflicting semantics, the result may be nonsensical. For example, a subtree with a checked checkbox and an unchecked checkbox will be presented as checked. All the labels will be merged into a single string with newlines separating each label from the other.

Conclusion:

In this article, we have been through What is MergeSemantics in Flutter along with how to implement it in a flutter.

That’s it for today.

Keep Fluttering !!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields