如何根据flutter中选择的项目列表返回容器?

esyap4oy  于 2023-01-09  发布在  Flutter
关注(0)|答案(3)|浏览(104)

我有一张清单

List<String> items = [
    "All",
    "Jobs",
    "Messages",
    "Customers",
  ];
  int current = 0;

这个列表直接负责我的标签栏:x1c 0d1x
当我点击选项卡栏中的一个项目时,我想在每个项目上返回一个不同的容器吗?
在flutch中我该怎么做呢?
我尝试在容器前面返回if语句,但似乎没有正确地得到该语句。
这是容器我想要到返回如果项目用户选择是全部,并且然后放条件在适当的地方为这rest项目.这是我放条件的方式但是它给我这错误

我的退货声明和代码-

current = 0 ??
Container(
            margin: const EdgeInsets.only(top: 30),
            height: MediaQuery.of(context).size.height * 1,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const SizedBox(
                  height: 10,
                ),
                Text(
                  items[current],
                  style: GoogleFonts.laila(
                      fontWeight: FontWeight.w500,
                      fontSize: 30,
                      color: Colors.deepPurple),
                ),
              ],
            ),
          ),
          current = 1 ?? Text('hello')

添加完整小窗口

class NotificationsView extends StatefulWidget {
  @override
  State<NotificationsView> createState() => _NotificationsViewState();
}

class _NotificationsViewState extends State<NotificationsView> {
  final controller = Get.put(NotificationsController());
  List<String> items = [
    "All",
    "Jobs",
    "Messages",
    "Customers",
  ];
  int current = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Notifications".tr,
          style: GoogleFonts.poppins(
              color: Color(0xff000000),
              fontSize: 16,
              fontWeight: FontWeight.w600),
        ),
        centerTitle: false,
        backgroundColor: Colors.transparent,
        elevation: 0,
        automaticallyImplyLeading: false,
        leadingWidth: 15,
        leading: new IconButton(
          icon: new Icon(Icons.arrow_back_ios, color: Color(0xff3498DB)),
          onPressed: () => {Get.back()},
        ),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
         
        },
        child: ListView(
          primary: true,
          children: <Widget>[
            filter(),
          ],
        ),
      ),
    );
  }

  Widget notificationsList() {
    return Obx(() {
      if (!controller.notifications.isNotEmpty) {
        return CircularLoadingWidget(
          height: 300,
          onCompleteText: "Notification List is Empty".tr,
        );
      } else {
        var _notifications = controller.notifications;
        return ListView.separated(
            itemCount: _notifications.length,
            separatorBuilder: (context, index) {
              return SizedBox(height: 7);
            },
            shrinkWrap: true,
            primary: false,
            itemBuilder: (context, index) {
              var _notification = controller.notifications.elementAt(index);
              if (_notification.data['message_id'] != null) {
                return MessageNotificationItemWidget(
                    notification: _notification);
              } else if (_notification.data['booking_id'] != null) {
                return BookingNotificationItemWidget(
                    notification: _notification);
              } else {
                return NotificationItemWidget(
                  notification: _notification,
                  onDismissed: (notification) {
                    controller.removeNotification(notification);
                  },
                  onTap: (notification) async {
                    await controller.markAsReadNotification(notification);
                  },
                );
              }
            });
      }
    });
  }

  Widget filter() {
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.all(5),
      child: Column(
        children: [
          /// CUSTOM TABBAR
          SizedBox(
            width: double.infinity,
            height: 60,
            child: ListView.builder(
                physics: const BouncingScrollPhysics(),
                itemCount: items.length,
                scrollDirection: Axis.horizontal,
                itemBuilder: (ctx, index) {
                  return Column(
                    children: [
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            current = index;
                          });
                        },
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          margin: const EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            color: current == index
                                ? Color(0xff34495E)
                                : Color(0xffF5F5F5),
                            borderRadius: BorderRadius.circular(11),
                          ),
                          child: Center(
                            child: Padding(
                              padding: const EdgeInsets.only(
                                  left: 10.0, right: 10.0, top: 5, bottom: 5),
                              child: Text(
                                items[index],
                                style: GoogleFonts.poppins(
                                    fontSize: 12,
                                    fontWeight: FontWeight.w500,
                                    color: current == index
                                        ? Colors.white
                                        : Colors.grey),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                }),
          ),

          /// MAIN BODY
          current = 0 ??
              Container(
                margin: const EdgeInsets.only(top: 30),
                height: MediaQuery.of(context).size.height * 1,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const SizedBox(
                      height: 10,
                    ),
                    Text(
                      items[current],
                      style: GoogleFonts.laila(
                          fontWeight: FontWeight.w500,
                          fontSize: 30,
                          color: Colors.deepPurple),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(
                          left: 20.0, right: 20.0, top: 20.0, bottom: 20),
                      child: Column(
                        children: [
                          Stack(
                            children: [
                              Row(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        color: Color(0xffEFFAFF),
                                        borderRadius:
                                            BorderRadius.circular(20)),
                                    child: Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Image.asset(
                                          'assets/icon/suitcase.png'),
                                    ),
                                  ),
                                  SizedBox(
                                    width: 15,
                                  ),
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        'New Job started ',
                                        style: GoogleFonts.poppins(
                                            fontSize: 14,
                                            fontWeight: FontWeight.w500,
                                            color: Color(0xff151515)),
                                      ),
                                      Text(
                                        'Tailoring for John Cletus  ',
                                        style: GoogleFonts.poppins(
                                            fontSize: 10,
                                            fontWeight: FontWeight.w400,
                                            color: Color(0xff151515)),
                                      ),
                                    ],
                                  ),
                                  Spacer(),
                                  Container(
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(2),
                                      color: Color(0xffFFE8E8),
                                    ),
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text(
                                        'Urgent',
                                        style: GoogleFonts.poppins(
                                            color: Color(0xffC95E5E)),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          Divider(
                            height: 5,
                            color: Color(0xffEFFAFF),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
          current = 1 ?? Text('hello')
        ],
      ),
    );
  }
}
6tdlim6h

6tdlim6h1#

如果要根据current索引显示不同类型的小工具,可以使用Builder

Builder(
  builder: (context) {
    switch (current) {
      case 0:
        return Container(
          margin: const EdgeInsets.only(top: 30),
          height: MediaQuery.of(context).size.height * 1,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(
                height: 10,
              ),
              Text(
                items[current],
                style: GoogleFonts.laila(
                    fontWeight: FontWeight.w500,
                    fontSize: 30,
                    color: Colors.deepPurple),
              ),
            ],
          ),
        );
      case 1:
        return Text('Hello');
      default:
        return SizedBox.shrink();
    }
  },
);
siotufzp

siotufzp2#

以下方法将解决您的问题。如果您需要进一步的帮助,请随时评论。

int _currentIndex = 0;
 var _containers = <Widget>[
    AllContainer(),
    JobsContainer(),
    MessagesContainer(),
    CustomerContainer(),
  ];
 Widget _bottomTab() {
    return BottomNavigationBar(
      currentIndex: _currentIndex,
      onTap: _onItemTapped, //
      type: BottomNavigationBarType.fixed,
      selectedLabelStyle: const TextStyle(color: Colors.blue),
      selectedItemColor: WAPrimaryColor,
      unselectedLabelStyle: const TextStyle(color: Colors.blue),
      unselectedItemColor: Colors.grey,
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(label: 'All'),
        
        BottomNavigationBarItem(
            label: 'Jobs'),
        BottomNavigationBarItem(
            label: 'Messages'),
        BottomNavigationBarItem( label: 'Customer'),
      ],
    );
  }

void _onItemTapped(int index) async {
    print('bottom  index::: $index');
    
      setState(() {
        _currentIndex = index;
      });
    
  }
 @override
  Widget build(BuildContext context) {
    

    return SafeArea(
      child: Scaffold(
        bottomNavigationBar: _bottomTab(),
        body: Center(child: _containers.elementAt(_currentIndex)),
      ),
    );
  }
uqcuzwp8

uqcuzwp83#

您可以在小部件级别使用条件if,
喜欢

/// MAIN BODY
if (current == 0)
  Container(
    margin: const EdgeInsets.only(top: 30),
    height: MediaQuery.of(context).size.height * 1,
    ...
  ),
if (current == 1) Text('hello')

也可以使用else if

if (current == 0)
  Container(
    margin: const EdgeInsets.only(top: 30),
    height: MediaQuery.of(context).size.height * 1,
  ) //you shouldnt put coma
else if (current == 1) Text('hello')
        ],
      ),
    );

但是创建一个单独的方法比将其放在这里更好

Widget getWidget(int index) {
    /// MAIN BODY
    if (current == 0) // or switch case
      return Container(
        margin: const EdgeInsets.only(top: 30),
        height: MediaQuery.of(context).size.height * 1,
      ); //you shouldnt put coma
    else if (current == 1) return Text('hello');
    return Text("default");
  }

并调用方法getWidget(current)
此外,还有一些小部件,如PageViewIndexedStack,将有助于组织代码结构

相关问题