仅用于控制Flutter的综合浏览量小部件或变量,仅用于一页

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

如何控制特定的小部件在网页浏览中隐藏或显示。在仅针对特定页面颤动的PageView Widget中,我们如何基于布尔值控制隐藏或显示的Widget。我们如何利用综合浏览量控制器执行此操作

flutter flutter-layout
1个回答
0
投票

您可以根据布尔值更改窗口小部件树中的子级。例如:child: condition ? WidgetWhenTrue : WidgetWhenFalse

更新

我发现的最好方法是,动态创建页面和子页面。您可以提供一个List<Widget>来代表最大值。内容,然后删除您不需要的小部件。或者,您可以将小部件动态添加到页面中。

import 'package:flutter/material.dart';

class PageViewWidget extends StatefulWidget {
  @override
  _PageViewWidgetState createState() => _PageViewWidgetState();
}

class _PageViewWidgetState extends State<PageViewWidget> {
  PageController _pageController;

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

  List<Text> maxContent = [
    Text('text 1'),
    Text('text 2'),
    Text('text 3'),
    Text('text 4'),
    Text('text 5'),
    Text('text 6')
  ];

  bool condition = true;

  Container dynamicPageChildren({Color color, List<int> delPos}) {
    Container newPage;
    List<Widget> newContent = List.from(maxContent);
    // modify your Widget List
    print('length = ${maxContent.length} ');
    for (int i in delPos.reversed) {
      // use reversed or provide the last elemt to remove first if not,
      // your list will shrink and the element you want to remove last does not exist or is the wrong one
      print('delete at pos $i');
      newContent.removeAt(i);
    }
    // add it to the page
    newPage = Container(
        color: color,
        child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: newContent));
    return newPage;
  }

  List<Container> dynamicPages({List<Color> colorList}) {
    // you could also pass the index positions into this function
    // or call your logic to decide which index should not be displayed
    List<Container> newPageList = [];
    // modify your Widget List
    int i = 0;
    for (Color color in colorList) {
      // example with given indices
      // newPageList.add(dynamicPageChildren(color: color, delPos: [1, 3, 5]));

      newPageList.add(dynamicPageChildren(color: color, delPos: [i]));
      i = i + 1;
    }

    return newPageList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: PageView(
            controller: _pageController,
            children: dynamicPages(
                colorList: [Colors.red, Colors.orange, Colors.yellow])),
      ),
    );
  }
}


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