Flutter- Expansion Panel for TextField

Issue

Expansion Panels in flutter are great. They require header and body along with isExpanded property to be declared to be able to construct an Expansion panel. Like this:

return new ExpansionPanel(
  headerBuilder: (BuildContext context, bool isExpanded){
                   return Text('header');},  
  isExpanded: false,
  body: new Text(body[enter image description here][1]),
);

I want to build an Expandable TextField. I can wrap the text field with Expansion panel, and specify the TextField as Body. But there is a big white space that between header and body. Also, I would like to just expand the body and remove the header altogether, so that I can see the first Text line of body without expanding, and the rest of the body opens up when I expand the Expansion panel. Does anyone know of any work arounds for this? Or any different widget or material component I can use.

Here is a screenshot of how it looks right now, see there is a lot of spacing in between header and body.

enter image description here

If this questions interests you, upvote it, to draw out better answers. Flutter has a lot to come, and we need a stronger stack overflow community.

Solution

I’m not sure the ExpansionPanel is what you want.

If I understood correctly, you want a Text with two states. In the first state the Text has only one line, in the second state the Text can display all its lines. When the user taps on this widget, it switches from one state to the other.

I created a simple widget for that:

class ExpandableText extends StatefulWidget {
  const ExpandableText(
    this.data, {
    Key key,
  }) : super(key: key);

  /// The text to display.
  ///
  /// This will be null if a [textSpan] is provided instead.
  final String data;

  @override
  _ExpandableTextState createState() => new _ExpandableTextState();
}

class _ExpandableTextState extends State<ExpandableText> {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleOnTap,
      child: new Text(
        widget.data,
        maxLines: _isExpanded ? null : 1,
      ),
    );
  }

  void _handleOnTap() {
    setState(() {
      _isExpanded = !_isExpanded;
    });
  }
}

There is no animations in here so it’s rather abrupt. Feel free to customize the above widget to fit your needs.

Answered By – Romain Rastel

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.