Flutter开发 组件的隐藏与显示
在Flutter中,可以使用Opacity
组件或Visibility
组件来控制子组件的显示和隐藏。Opacity
组件通过改变不透明度来控制子组件的显示和隐藏,而Visibility
组件则可以直接设置子组件是否可见。
以下是使用这两种组件的示例代码:
使用Opacity
组件:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
double opacity = 1.0; // 不透明度,1.0 表示完全不透明
void _toggleOpacity() {
setState(() {
opacity = opacity == 0.0 ? 1.0 : 0.0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Opacity Example'),
),
body: Center(
child: Opacity(
opacity: opacity,
child: FlatButton(
onPressed: _toggleOpacity,
child: Text('Toggle Opacity'),
),
),
),
);
}
}
使用Visibility
组件:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool isVisible = true; // 是否可见
void _toggleVisibility() {
setState(() {
isVisible = !isVisible;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Visibility Example'),
),
body: Center(
child: Visibility(
visible: isVisible,
child: FlatButton(
onPressed: _toggleVisibility,
child: Text('Toggle Visibility'),
),
),
),
);
}
}
在这两个示例中,我们有一个按钮,点击后会更改不透明度或可见性状态。Opacity
组件通过动态改变不透明度实现组件的显示和隐藏,而Visibility
组件直接通过visible
属性进行控制。
评论已关闭