动态切换支架主体

时间:2019-11-21 12:26:22

标签: flutter dart

我有一个内部有scaffoldBottomNavigationBar的应用程序。

现在,我想根据点击来更改body中的scaffold

首先,我认为我应该使用变量来存储BodyLayout || CatListLayout。

但是它不起作用。我该怎么办??

Widget build(BuildContext context) {
    return Scaffold(

    body: BodyLayout(articles),  // it works
  //body: CatListLayout(cats), // and it al so works

      bottomNavigationBar: BottomNavigationBar(
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text('article'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.business),
          title: Text('cat'),
        ),
      ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
}

void _onItemTapped(int index) {
    if (index == 0){
     // want to change body to BodyLayout
    }
    if ( index == 1){
     // want to change body to CatListLayout
    }

}  
class BodyLayout extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
        /////
        );
    }
}
class CatListLayout extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
        return ListView.builder(
        ////
        );
    }
}

2 个答案:

答案 0 :(得分:1)

最简单的方法是这样,但是由于没有使用导航器,因此没有任何后退按钮控件。请记住这一点。与使用不同的脚手架相比,使用导航器处理体内的此类子页面要棘手得多。

import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  int myIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: myIndex == 0 ? BodyLayout(articles) : CatListLayout(cats), 
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('article'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('cat'),
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
      ),
    );
  }

  void _onItemTapped(int index) {
    if (index == 0) {
      setState(() {
        myIndex = 0;
      });
    }
    if (index == 1) {
      setState(() {
        myIndex = 1;
      });
    }
  }
}

class BodyLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        /////
        );
  }
}

class CatListLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        ////
        );
  }
}

答案 1 :(得分:0)

所以有几种方法可以做到这一点。单击按钮时,可以使用PageView小部件并控制其控制器。另一个选择是为此存储当前页面的索引,整个页面小部件应该是有状态的。单击按钮后,您可以更改此索引并调用setState来重建小部件。构建窗口小部件时,请查看当前索引并显示与此索引关联的内容