在開發 App 的過程中,有時一個頁面難以放下所有需要的元件。這時候,或許我們可以考慮將頁面其中一個區塊製作成可滑動、可延展的佈局。
在 Flutter 中,我們可以透過 SingleChildScrollView
佈局元件來做到這件事。所有要顯示在可滑動區域的元件,通通放在其 child
屬性底下即可。
範例程式碼
下方是一個簡單的範例程式碼。我將主要的頁面透過 Expanded
分成三個區塊,其中,只有中間的 SingleChildScrollView
區塊是可以滑動、展示大量元件的。
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; // Main void main() => runApp(MyApp()); // MyApp class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } } // HomePage class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("SingleChildScrollView Demo"), ), body: Column( children: <Widget>[ // Upper component // ======================================================== Expanded( child: Container( alignment: Alignment.center, width: MediaQuery.of(context).size.width, color: Colors.grey, child: Text("Upper component"), ), flex: 1, ), // ======================================================== // SingleChildScrollView // ======================================================== Expanded( child: SingleChildScrollView( child: Column( children: List.generate(20, (index) { return ElevatedButton( child: Text("Button ${index+1}"), onPressed: () => Null, ); }), ), ), flex: 1, ), // ======================================================== // Lower component // ======================================================== Expanded( child: Container( alignment: Alignment.center, width: MediaQuery.of(context).size.width, color: Colors.grey, child: Text("Lower component"), ), flex: 1, ), // ======================================================== ], ) ); } }
Output:
References
- https://stackoverflow.com/questions/51765092/how-to-scroll-page-in-flutter
- https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html