7 простых способов создания адаптивных макетов во Flutter

«Flutter адаптивный простой» можно перевести как «Как легко создавать адаптивные макеты во Flutter». Вот несколько методов с примерами кода для создания адаптивных макетов во Flutter:

Метод 1: LayoutBuilder

LayoutBuilder(
  builder: (BuildContext context, BoxConstraints constraints) {
    if (constraints.maxWidth > 600) {
      // Wide layout
      return Container(
        width: 200,
        height: 100,
        color: Colors.blue,
      );
    } else {
      // Narrow layout
      return Container(
        width: 100,
        height: 50,
        color: Colors.red,
      );
    }
  },
);

Метод 2: MediaQuery

Container(
  width: MediaQuery.of(context).size.width > 600 ? 200 : 100,
  height: MediaQuery.of(context).size.width > 600 ? 100 : 50,
  color: MediaQuery.of(context).size.width > 600 ? Colors.blue : Colors.red,
);

Метод 3: OrientationBuilder

OrientationBuilder(
  builder: (BuildContext context, Orientation orientation) {
    if (orientation == Orientation.landscape) {
      // Landscape layout
      return Container(
        width: 200,
        height: 100,
        color: Colors.blue,
      );
    } else {
      // Portrait layout
      return Container(
        width: 100,
        height: 50,
        color: Colors.red,
      );
    }
  },
);

Метод 4: пакет Sizer

import 'package:sizer/sizer.dart';
Container(
  width: 15.w, // 15% of the screen width
  height: 7.h, // 7% of the screen height
  color: Colors.blue,
);

Метод 5: адаптивные платформы (например, Flutter ScreenUtil)

import 'package:flutter_screenutil/flutter_screenutil.dart';
Container(
  width: ScreenUtil().setWidth(200),
  height: ScreenUtil().setHeight(100),
  color: Colors.blue,
);

Метод 6: ограничения и LayoutBuilder

Container(
  width: constraints.maxWidth * 0.5, // 50% of the available width
  height: constraints.maxHeight * 0.5, // 50% of the available height
  color: Colors.blue,
);

Метод 7: расширенный и гибкий

Row(
  children: [
    Expanded(
      flex: 1,
      child: Container(
        height: 100,
        color: Colors.red,
      ),
    ),
    Expanded(
      flex: 2,
      child: Container(
        height: 100,
        color: Colors.blue,
      ),
    ),
  ],
);