How To Use Custom Single Child Layout Widget Using Flutter

admin_img Posted By Bajarangi soft , Posted On 06-11-2020

A widget that defers the layout of its single child to a delegate.The delegate can determine the layout constraints for the child and can decide where to position the child. The delegate can also determine the size of the parent, but the size of the parent cannot depend on the size of the child.

How To Use Custom Single Child Layout Widget Using Flutter

custom single child layout widget
Complete Code For custom single child layout widget In Flutter
main.dart

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.deepPurple[600],
          title: Text("Custom Single Child Layout Widget"
          )),
      body: Container(
        height: 100.0,
        width: 100.0,
        color: Colors.deepPurple[300],
        child: CustomSingleChildLayout(
          delegate: _MySingleChildLayoutDelegate(
            widgetSize: size,
          ),
        ),
      ),
    );
  }
}

class _MySingleChildLayoutDelegate extends SingleChildLayoutDelegate {
  _MySingleChildLayoutDelegate({@required this.widgetSize});
  final Size widgetSize;
  @override
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
    return BoxConstraints.expand(width: 120.0, height: 120.0);
  }
  @override
  Offset getPositionForChild(Size size, Size childSize) {
    return Offset(widgetSize.width / 2, widgetSize.height / 2);
  }
  @override
  bool shouldRelayout(_MySingleChildLayoutDelegate oldDelegate) {
    return widgetSize != oldDelegate.widgetSize;
  }
}

Related Post