飞道的博客

flutter CustomSingleChildLayout Demo

266人阅读  评论(0)

今天看到flutter官方介绍flutter的PPT上一个小案例,演示 flutter 自定义布局能力,然后自己动手写了一下。

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

class CustomLayoutDemo extends StatefulWidget {
  @override
  _CustomLayoutDemoState createState() => _CustomLayoutDemoState();
}

class _CustomLayoutDemoState extends State<CustomLayoutDemo> {
  int _count = 0;
  TextEditingController _editingController;

  @override
  void initState() {
    super.initState();
    _editingController = TextEditingController()
      ..addListener((){
        setState(() {
          _count = _editingController.text.length;
        });
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(),
      body: Column(
        children: <Widget>[
          TextField(
            maxLength: 40,
            controller: _editingController,
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: 100,
            child: CustomSingleChildLayout(
                delegate: MyDelegate(count: _count, maxLength: 40),
                child: Image.asset('assets/test.png',width: 30,height: 30,),
              ),
          )
        ],
      ),
    );
  }
}

class MyDelegate extends SingleChildLayoutDelegate {
  final int count;
  final int maxLength;

  MyDelegate({@required this.count, this.maxLength: 10});
  @override
  bool shouldRelayout(SingleChildLayoutDelegate oldDelegate) {
    return true;
  }

  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return BoxConstraints( 
      maxHeight: 50,
      maxWidth: 50
    );
  }
  
  @override
  Offset getPositionForChild(Size size, Size childSize) {
    final double maxX = size.width - childSize.width;
    final double maxH = size.height - childSize.height;
    return Offset(maxX * count / maxLength, sin(count) * maxH / 4 + maxH / 4); 
  }
}


转载:https://blog.csdn.net/qq_40928212/article/details/104639250
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场