在 PageView 中使用浮动操作按钮

问题描述 投票:0回答:3

我尝试在 PageView 中使用 Flutter FAB,但由于 FAB 采用在页面 2 中初始化的变量,因此会产生错误。

那么如何才能只在第二页之后显示FAB呢?

flutter floating-action-button flutter-pageview
3个回答
1
投票

您可以在顶层使用 PageView,并在每个项目上使用脚手架。也可以通过在 pageController 中添加侦听器来完成。


class FabG extends StatefulWidget {
  const FabG({super.key});

  @override
  State<FabG> createState() => _FabGState();
}

class _FabGState extends State<FabG> {
  bool isFabActivePage = false;

  late final PageController controller = PageController()
    ..addListener(() {
      if (controller.hasClients && (controller.page ?? 0) < 2) { //your logic here
        isFabActivePage = false;
        setState(() {});
      } else if (isFabActivePage == false) {
        isFabActivePage = true;
        setState(() {});
      }
    });

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:
          isFabActivePage ? FloatingActionButton(onPressed: () {}) : null,
      body: PageView.builder(
        controller: controller,
        itemBuilder: (context, index) => Center(child: Text("page ${index+1}")),
      ),
    );
  }
}

0
投票

我使用的解决方案是设置一个 bool 浮动的回调。

在主页上:

`

bool floating = false;
showFAB(show) {
    setState(() {
      floating = show;
    });
  }`

 floatingActionButton:(floating) ? FloatingMenu(pageController: pageController) : null,

然后在第二页的

initState
函数中使用回调来更改布尔值


0
投票

Scaffold
中,只为您感兴趣的页面提供一个实际的按钮。不是必需的,但一个舒适的方法是使用函数来构建FAB:

Scaffold(
  ...
  floatingActionButton: buildFAB(),

在该函数中:

Widget? buildFAB() {
  if (currentPage == 2)
    return FloatingActionButton(
      onPressed: () {
        ...
      },
      child: const Icon(Icons.whatever),
    );
  else
    return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.