Irbisa · Шпаргалка
Базовые виджеты
Основные виджеты макета: Container, Row, Column, Stack, ListView
В чём разница между
Container,SizedBox,PaddingиColoredBox?Что произойдёт при построении этого
Containerи как это исправить?Container( color: Colors.white, padding: const EdgeInsets.all(16), decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), ), child: const Text('Card'),)Что в
RowиColumnзадаютmainAxisAlignment,crossAxisAlignmentиmainAxisSize?Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, // required for baseline children: [ Text('Total', style: Theme.of(context).textTheme.titleMedium),…В чём разница между
ExpandedиFlexible?// Expanded: both panels fill the row, 1/3 and 2/3Row( children: [ Expanded(child: Container(color: Colors.red)), Expanded(flex: 2, child: Container(color: Colors.blue)), ],…Что делают
AspectRatio,FittedBoxиConstrainedBoxи когда каждый из них нужен?// 16:9 box at any screen widthAspectRatio( aspectRatio: 16 / 9, child: Image.network(thumbnailUrl, fit: BoxFit.cover),)…Как работает
Stackвместе сPositionedи когда его выбирают вместоRowилиColumn?// A caption over a photo: the image sets the Stack's sizeStack( children: [ Image.asset('assets/cover.jpg'), const Positioned.fill( child: DecoratedBox(…Что делает
Wrapи чем он отличается отRow, который переполняется?Wrap( spacing: 8, // between chips in a line runSpacing: 8, // between lines children: [ for (final tag in tags) Chip(label: Text(tag)), ],…Этот ряд работает с короткими именами, но ломается на длинных. Какая ошибка появится и как её исправить?
Row( children: const [ Icon(Icons.person), SizedBox(width: 8), Text('Konstantin Konstantinopolsky-Vasilevsky, Senior Software Engineer, Platform Team'), Icon(Icons.chevron_right), ],)Что делает
SafeAreaи куда его ставить?В чём разница между
ListView(children: ...),ListView.builderиColumnвнутриSingleChildScrollView?// Data-driven list: rows are built only when they come into viewListView.builder( itemCount: messages.length, itemExtent: 72, // every row is 72 px: cheap jumps and scrollbar itemBuilder: (context, index) => MessageTile(message: messages[index]),)…В чём разница между
Visibility,OpacityиOffstage?Какие кнопки есть в Material 3 и когда какую выбирать?
Почему
InkWellвнутри цветногоContainerне показывает рябь и что использовать вместо этого?// No visual feedback; opaque makes the whole padded box tappableGestureDetector( behavior: HitTestBehavior.opaque, onTap: _select, child: const Padding(padding: EdgeInsets.all(12), child: Text('Tap me')),)…Как показать картинку из ассетов, сети, памяти и файла и чем
Image.networkотличается отNetworkImage?// pubspec.yaml -> flutter: assets: [assets/images/]Image.asset('assets/images/logo.png', width: 96) Image.network( 'https://cdn.example.com/avatar.jpg', width: 64,…Как показать
SnackBarи зачем нуженScaffoldMessenger?ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar( SnackBar( content: const Text('Message archived'), behavior: SnackBarBehavior.floating,…Как сделать вкладки на
TabBar,TabBarViewиDefaultTabController?DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: const Text('Orders'), bottom: const TabBar(…Объясните правило «ограничения идут вниз, размеры идут вверх, позицию задаёт родитель». Почему
width: 300уContainerиногда игнорируется?// wrong: SizedBox.expand forces the full size, so 300 is clampedSizedBox.expand( child: Container(width: 300, height: 120, color: Colors.teal), // fills everything); // right: Center loosens the constraints, so the child may be smaller…ListViewвнутриColumnпадает с ошибкой вёрстки. В чём причина и как это исправить?// wrong: Vertical viewport was given unbounded heightColumn( children: [ const ProfileHeader(), ListView.builder(itemCount: items.length, itemBuilder: _row), ],…Как
GridViewопределяет высоту плитки и почему плитки переполняются на более узком телефоне?// wrong: height comes from width, so large text or a narrow phone overflowsGridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 0.72, ),…Нажатие на эту кнопку бросает «Scaffold.of() called with a context that does not contain a Scaffold». Почему и как исправить?
class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( drawer: const Drawer(child: Text('Menu')), body: Center( child: TextButton( onPressed: () => Scaffold.of(context).openDrawer(), child: const Text('Open menu'), ), ), ); }}Найдите баг: после переключения на другую нижнюю вкладку и обратно лента прыгает наверх и снова загружает данные.
class _HomeShellState extends State<HomeShell> { int _index = 0; static const _pages = [FeedPage(), SearchPage(), ProfilePage()]; @override Widget build(BuildContext context) { return Scaffold( body: _pages[_index], bottomNavigationBar: NavigationBar( selectedIndex: _index, onDestinationSelected: (i) => setState(() => _index = i), destinations: _destinations, ), ); }}В чём разница между неявными и явными анимациями и с каких стоит начинать?
// Implicit: change the value, Flutter animates to itAnimatedContainer( duration: const Duration(milliseconds: 250), curve: Curves.easeOut, width: _expanded ? 240 : 120, color: _expanded ? Colors.teal : Colors.grey,…Как работает
CustomPainterи когда его использовать?import 'dart:math' as math; class RingPainter extends CustomPainter { RingPainter({required this.progress, required this.color}); final double progress; // 0.0 to 1.0…Найдите баг: кольцо загрузки застывает на первом значении, хотя родитель вызывает
setStateи передаёт новыйRingPainter(_progress).class RingPainter extends CustomPainter { RingPainter(this.progress); final double progress; // 0.0 to 1.0 @override void paint(Canvas canvas, Size size) { final paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 8; final rect = (Offset.zero & size).deflate(4); canvas.drawArc(rect, -math.pi / 2, progress * 2 * math.pi, false, paint); } @override bool shouldRepaint(RingPainter oldDelegate) => false;}