flutter CustomSingleChildLayout Demo

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

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

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

class _CustomLayoutDemoState extends State {
  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: [
          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); 
  }
}

你可能感兴趣的:(flutter)