Нарисуйте изображение после изображения, загруженного из сети - PullRequest
0 голосов
/ 30 апреля 2019

Я загружаю изображения из вызова API и затем показываю изображение и некоторые данные в виде списка в флаттере и рисуя ограничивающую рамку на изображении, но так как мое изображение загружается из URL, мой пользовательский интерфейс нарушается, Как я могу гарантировать, что Canvas будет рисовать после загрузки изображения с URL-адреса сети в макете флаттера. Есть ли какие-либо обратные вызовы, которые я могу использовать.

class ListPage extends StatefulWidget {
  ListPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ListPageState createState() => _ListPageState();
}
class _ListPageState extends State<ListPage> {
  Future<List<ProcessedInference>> processInference;

  @override
  void initState() {
    processInference = localInference();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final toAppBar = AppBar(
      elevation: 0.1,
      backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
      title: Text(widget.title),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.list),
          onPressed: () {},
        )
      ],
    );

    Card makeCard(ProcessedInference pro) => Card(
          elevation: 2.0,
          margin: new EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
          child: Container(
            child: Column(
              children: <Widget>[
                CustomPaint(
                  size: Size(640.0, 480.0),
                  foregroundPainter: RectPainter(pro.boundingBox),
                  child: Image.network(pro.frameUrl),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 8.0,
                    ),
                    Text(
                      "Spotted:  ${pro.peopleCount}",
                      style: TextStyle(fontSize: 16.0),
                      textAlign: TextAlign.start,
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    Text(
                      "Spotted on : ${pro.timeStamp}",
                      style: TextStyle(fontSize: 16.0),
                      textAlign: TextAlign.start,
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                  ],
                ),
              ],
            ),
          ),
        );

    final makeBody = Container(
      child: FutureBuilder<List<ProcessedInference>>(
        future: processInference,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            print("Has data");
            if (snapshot.data == null || snapshot.data.length <= 0) {
              return Center(
                  child: Text("No results", textAlign: TextAlign.center));
            } else {
              return ListView.builder(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return makeCard(snapshot.data[index]);
                  });
            }
          } else if (snapshot.hasError) {
            print("has error ");
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        },
      ),
    );

    return Scaffold(
      appBar: toAppBar,
      body: makeBody,
    );
  }
}

class RectPainter extends CustomPainter {
  final List<List<double>> boundingBox;

  RectPainter(this.boundingBox);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.deepOrange;
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 2.0;

    final boxPaint = Paint();
    boxPaint.color = Colors.amberAccent;
    boxPaint.style = PaintingStyle.fill;
    boxPaint.strokeWidth = 2.0;

    for (var i = 0; i < boundingBox.length; i++) {
      var confidence = boundingBox[i][0];
      var left = boundingBox[i][1] * size.width;
      var top = boundingBox[i][2] * size.height;
      var right = boundingBox[i][3] * size.width;
      var bottom = boundingBox[i][4] * size.height;

      var rect = Rect.fromLTRB(left, top - 15, right, bottom);
      canvas.drawRect(rect, paint);

      TextSpan span = new TextSpan(
          style: new TextStyle(color: Colors.red[600], fontSize: 10.0),
          text: confidence.toStringAsFixed(2));
      TextPainter tp = new TextPainter(
          text: span,
          textAlign: TextAlign.center,
          textDirection: TextDirection.ltr);
      tp.layout();
      canvas.drawRect(
          Rect.fromLTRB(
              rect.left, rect.top, rect.left + tp.width, rect.top + tp.height),
          boxPaint);
      tp.paint(canvas, new Offset(rect.left, rect.top));
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
...