仅可在Flutter中的某些小部件中滑动

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

我在Flutter中看到了PageView,它可以正确地在不同页面之间滑动。但是我们可以在当前页面的任意位置滑动以向左或向右移动。但是我的问题是仅在某些区域内左右滑动。如何实现?

enter image description here

在上图中,我只想在蓝色容器中向左或向右滑动。

flutter flutter-layout
1个回答
0
投票

我可以使用以下代码来解决上述问题:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AccountScreen(),
    );
  }
}

class AccountScreen extends StatefulWidget {
  @override
  _AccountScreenState createState() => _AccountScreenState();
}

class _AccountScreenState extends State<AccountScreen> {
  PageController _bannerController = PageController(
    initialPage: 0,
  );

  PageController _contentController = PageController(
    initialPage: 0,
  );

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: PageView(
              controller: _bannerController,
              onPageChanged: (int value) {
                _contentController.animateToPage(value,
                    duration: Duration(milliseconds: 400),
                    curve: Curves.easeInOut);
              },
              children: [
                MyPage1Widget(),
                MyPage2Widget(),
              ],
            ),
          ),
          Expanded(
            flex: 2,
            child: PageView(
              physics: NeverScrollableScrollPhysics(),
              controller: _contentController,
              children: [
                MyPage1Widget(),
                MyPage2Widget(),
              ],
            ),
          )
        ],
      ),
    );
  }
}

class MyPage1Widget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text("Page 1"),
    );
  }
}

class MyPage2Widget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text("Page 2"),
    );
  }
}

让我知道是否有比这更好的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.