Overlay a line on top of a component in Flutter

2019-07-18 07:45发布

问题:

I have the following layout in one of my components and would like to put a line on top of that like this:

That is my current code and already searched through the API documentation of Flutter for a while now and didn't find something suitable to achieve that.

new Row(
  children: <Widget>[
    new Expanded(
      child: const Text("Some text"),
    ),
    const Text("Some other text"),
  ],
)

Any pointers or ideas how to do that?

回答1:

Okay. Got it working by using a custom Decoration.
Here is my code:

class StrikeThroughDecoration extends Decoration {
  @override
  BoxPainter createBoxPainter([VoidCallback onChanged]) {
    return new _StrikeThroughPainter();
  }
}

class _StrikeThroughPainter extends BoxPainter {
  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final paint = new Paint()
      ..strokeWidth = 1.0
      ..color = Colors.black
      ..style = PaintingStyle.fill;

    final rect = offset & configuration.size;
    canvas.drawLine(new Offset(rect.left, rect.top + rect.height / 2), new Offset(rect.right, rect.top + rect.height / 2), paint);
    canvas.restore();
  }
}

Used like that in my component:

new Container(
  foregroundDecoration: new StrikeThroughDecoration(),
  child: new Row(
    children: <Widget>[
      new Expanded(
        child: const Text("Some text"),
      ),
      const Text("Some other text"),
    ],
  )
)


回答2:

You could use a Stack with a Divider.

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

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text('Example App')),
      body: new Padding(
        padding: new EdgeInsets.all(5.0),
        child: new Center(
          child: new Stack(
            children: <Widget>[
              new Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  new Text('Hello world'),
                  new Text('Some other text'),
                ],
              ),
              new Positioned.fill(
                left: 0.0,
                right: 0.0,
                child: new Divider(color: Colors.black),
              )
            ],
          ),
        ),
      ),
    );
  }
}


标签: dart flutter