我有里面有一个scaffoldBottomNavigationBar的应用程序。

现在我想根据点击更改bodyscaffold

首先,我认为我应该使用变量来存储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(
        ////
        );
    }
}

最佳答案

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

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(
        ////
        );
  }
}

10-06 08:01