滚动容器:SingleChildScrollView

SingleChildScrollView 是 Flutter 中最简单的滚动容器之一。它的特点就是:只能包含一个子组件(child),但这个子组件可以超出屏幕范围,从而支持滚动

适合用于:内容不会特别多,但可能在小屏幕设备上超出一屏的场景。

SingleChildScrollView({
  Key? key,
  this.scrollDirection = Axis.vertical, // 滚动方向(默认纵向)
  this.reverse = false,                 // 是否反向滚动
  this.padding,                         // 内边距
  this.primary,                         // 是否使用主滚动控制器
  this.physics,                         // 滚动物理效果(如回弹)
  this.controller,                      // 滚动控制器
  this.clipBehavior = Clip.hardEdge,    // 超出部分裁剪方式
  required Widget child,                // 唯一子组件
})

scrollDirection

  • Axis.vertical:纵向滚动(默认)
  • Axis.horizontal:横向滚动

reverse

  • 是否反向,比如 true 时,内容从下往上滚动。

physics

  • 控制滚动物理效果:
    • BouncingScrollPhysics():iOS 风格的回弹效果
    • ClampingScrollPhysics():Android 风格(到边界会停住)

controller

  • 传入 ScrollController,可以手动控制滚动位置。
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text("SingleChildScrollView 示例")),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(16), // 给内容加内边距
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: List.generate(
              20, // 生成 20 个彩色容器
              (index) => Container(
                height: 80,
                margin: const EdgeInsets.only(bottom: 12),
                color: Colors.primaries[index % Colors.primaries.length],
                child: Center(
                  child: Text(
                    "第 $index 个条目",
                    style: const TextStyle(fontSize: 18, color: Colors.white),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

×

喜欢就点赞,疼爱就打赏