использовать нижнюю навигацию для переключения между файлами дротиков в флаттере - PullRequest
1 голос
/ 27 февраля 2020

Я использовал этот пример кода для создания нижней панели навигации, и теперь он работает. Я хочу, чтобы я нажимал на каждый элемент, показывая другой файл дротика и по умолчанию показывая первую страницу, но в этом коде использовал кнопку показа для любой страницы. теперь я хочу знать, как я могу это сделать?

спасибо всем

вот код:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:store/pages/category.dart';
import 'package:store/pages/index_shop.dart'; 


void main() {
 runApp(
 MaterialApp(localizationsDelegates: [
  GlobalMaterialLocalizations.delegate,
  GlobalWidgetsLocalizations.delegate,
], supportedLocales: [
  Locale("en", "US"),
  Locale("fa", "IR"), // OR Locale('ar', 'AE') OR Other RTL locales
], debugShowCheckedModeBanner: false, home: Home()),
);
}

class Home extends StatefulWidget {
 @override
 State<StatefulWidget> createState() {
  return HomeState();
 }
 }

 class HomeState extends State<Home> {
   bool clickedCentreFAB = false; 
   int selectedIndex = 0; //to handle which item is currently selected in the bottom app bar
   String text = "Home";

  void updateTabSelection(int index, String buttonText) {
    setState(() {
    selectedIndex = index;
    text = buttonText;
    });
    }

   @override
   Widget build(BuildContext context) {
    return Scaffold(
     body: Stack(
     children: <Widget>[
       Align(
        alignment: FractionalOffset.center,

        child: RaisedButton(
          child: Text(text),
          onPressed: () {},
        ),
      ),

      Align(
        alignment: FractionalOffset.bottomCenter,
        child: AnimatedContainer(
          duration: Duration(milliseconds: 250),
          //if clickedCentreFAB == true, the first parameter is used. If it's false, the second.
          height:
          clickedCentreFAB ? MediaQuery.of(context).size.height : 10.0,
          width: clickedCentreFAB ? MediaQuery.of(context).size.height : 10.0,
          decoration: BoxDecoration(
              borderRadius:
              BorderRadius.circular(clickedCentreFAB ? 0.0 : 300.0),
              color: Colors.blue),
            ),
            )
            ],
            ),
            floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, 
            floatingActionButton: FloatingActionButton(
             onPressed: () {
             setState(() {
             clickedCentreFAB = !clickedCentreFAB; //to update the animated container
            });
             },
            tooltip: "Centre FAB",
            child: Container(
            margin: EdgeInsets.all(15.0),
            child: Icon(Icons.live_tv),
             ),
            elevation: 4.0,
             ),
             bottomNavigationBar: BottomAppBar(
             child: Container(
              margin: EdgeInsets.only(left: 12.0, right: 12.0),
            child: Row(
            mainAxisSize: MainAxisSize.max,
             mainAxisAlignment: MainAxisAlignment.spaceBetween,
             children: <Widget>[
           IconButton(
            //update the bottom app bar view each time an item is clicked
            onPressed: () {
              updateTabSelection(0, "Home");
            },
            iconSize: 27.0,
            icon: Icon(
              Icons.shopping_cart,
              //darken the icon if it is selected or else give it a different color
              color: selectedIndex == 0
                  ? Colors.blue.shade900
                  : Colors.grey.shade400,
            ),
          ),
          IconButton(
            onPressed: () {
              updateTabSelection(1, "Outgoing");
            },
            iconSize: 27.0,
            icon: Icon(
              Icons.dashboard,
              color: selectedIndex == 1
                  ? Colors.blue.shade900
                  : Colors.grey.shade400,
            ),
          ),
          //to leave space in between the bottom app bar items and below the FAB
          SizedBox(
            width: 50.0,
          ),
          IconButton(
            onPressed: () {
              updateTabSelection(2, "Incoming");
            },
            iconSize: 27.0,
            icon: Icon(
              Icons.shopping_basket,
              color: selectedIndex == 2
                  ? Colors.blue.shade900
                  : Colors.grey.shade400,
            ),
          ),
          IconButton(
            onPressed: () {
              updateTabSelection(3, "Settings");
            },
            iconSize: 27.0,
            icon: Icon(
              Icons.person,
              color: selectedIndex == 3
                  ? Colors.blue.shade900
                  : Colors.grey.shade400,
            ),
          ),
        ],
      ),
    ),
    //to add a space between the FAB and BottomAppBar
    shape: CircularNotchedRectangle(),
    //color of the BottomAppBar
    color: Colors.white,
  ),
);
 }
  }

1 Ответ

1 голос
/ 28 февраля 2020

Вы можете использовать Навигатор по методу "onPressed" для кнопки значков, шаг 1, создать onGenerateRoute для MaterialApp

return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: APP_NAME,
      home: GetStarted(),
      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
          case "category":
            return CupertinoPageRoute(
              builder: (BuildContext context) {
                return Category();
              },
              settings: settings,
            );
            break;

          case "index":
            return CupertinoPageRoute(
                builder: (BuildContext context) {
                  return Index();
                },
                settings: settings);
           break;
         }
      }
   );

, шаг 2 добавить навигацию в IconButton, метод onPressed

        Navigator.of(context).pushNamed("category");

...