这是一个 main.dart 示例,它使用LayoutBuilder 将脚手架(body 和 appBar)限制为最小 480dp,如果宽度限制小于该值,则将脚手架包裹在水平的 @987654324 内@ 和 ScrollBar。如果约束高度小于 480dp,它会将脚手架(可能已经被包裹,也可能没有)包裹在垂直滚动中。
如果宽度和高度都小于 480dp,则可以看到 2 个滚动条。在这种情况下,小部件树必须是ScrollBar > ScrollBar > ScrollView > ScrollView。如果widget tree是ScrollBar > ScrollView > ScrollBar > ScrollView,则嵌套的Scrollbar只有在父ScrollBar滚动到边缘时才可见。
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(
// set default isAlwaysShown, so don't need to set for individual Scrollbar.
theme: ThemeData(scrollbarTheme: ScrollbarThemeData(isAlwaysShown: true)),
home: App(),
));
}
class App extends StatefulWidget {
@override
AppState createState() => AppState();
}
class AppState extends State<App> {
final minWidth = 480.0;
final minHeight = 480.0;
ScrollController _horizontalController = ScrollController();
ScrollController _verticalController = ScrollController();
@override
void dispose() {
_horizontalController.dispose();
_verticalController.dispose();
super.dispose();
}
Widget _buildScaffold() {
return Scaffold(
appBar: AppBar(title: Text('2D Scrollbars')),
body: Container(color: Colors.amber),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.school), label: 'School'),
],
),
);
}
@override
Widget build(BuildContext context) {
final scaffold = _buildScaffold();
return LayoutBuilder(
builder: (context, constraints) {
final horizontalScrollbarEnabled = constraints.minWidth < minWidth;
final verticalScrollbarEnabled = constraints.minHeight < minHeight;
if (horizontalScrollbarEnabled && verticalScrollbarEnabled) {
return Scrollbar(
controller: _horizontalController,
child: Scrollbar(
// IMPORTANT: this scrollbar only handle notification of the vertical ScrollView.
// The first ScrollView (depth = 0), is the horizontal one.
// The second ScrollView (depth = 1), is the vertical one.
// If notification.depth != 1, the notification is bubble up to horizontal Scrollbar.
notificationPredicate: (notification) => notification.depth == 1,
controller: _verticalController,
child: SingleChildScrollView(
controller: _horizontalController,
scrollDirection: Axis.horizontal,
child: SingleChildScrollView(
controller: _verticalController,
child: Container(
width: minWidth,
height: minHeight,
child: scaffold,
),
),
),
),
);
} else if (horizontalScrollbarEnabled) {
return Scrollbar(
controller: _horizontalController,
child: SingleChildScrollView(
controller: _horizontalController,
scrollDirection: Axis.horizontal,
child: Container(
width: minWidth,
child: scaffold,
),
),
);
} else if (verticalScrollbarEnabled) {
return Scrollbar(
controller: _verticalController,
child: SingleChildScrollView(
controller: _verticalController,
child: Container(
height: minHeight,
child: scaffold,
),
),
);
}
return scaffold;
},
);
}
}