ListView как TabBar во флаттере - PullRequest
0 голосов
/ 03 мая 2020

Я пытаюсь создать горизонтальный ListView как своего рода «контроллер» для моего TabBar View. Как сделать так, чтобы при нажатии на одну из кнопок FlatBut она меняла вкладку. И можно ли изменить цвет текста в кнопке в зависимости от того, открыт он или нет?

Ниже приведен мой код, и я хочу добавить его в качестве кода

. Код:

import 'package:Auszeit/services/auszeit_icons_icons.dart';
import 'package:Auszeit/widgets/auszeitDrawer.dart';
import 'package:Auszeit/widgets/order/itemCard.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class OrderPage extends StatefulWidget {
  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage>
    with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    TabController _tabController;
    ScrollController _scrollController;

    @override
    void initState() {
      _tabController = TabController(vsync: this, length: 4);
      _scrollController = ScrollController();
      super.initState();
    }

    return DefaultTabController(
        length: 4,
        child: Scaffold(
          floatingActionButton: FloatingActionButton(
            onPressed: () {},
            elevation: 15,
            child: Icon(
              Icons.shopping_basket,
              color: Colors.green[800],
            ),
            backgroundColor: Colors.white,
          ),
          appBar: AppBar(
            elevation: 0,
            backgroundColor: Colors.white,
            leading: Builder(
              builder: (context) {
                return IconButton(
                  icon: Icon(
                    Icons.menu,
                    color: Colors.grey,
                  ),
                  onPressed: () => AuszeitDrawer.of(context).open(),
                );
              },
            ),
            title: Text(
              "Auszeit eSG",
              style: TextStyle(
                color: Colors.green[800],
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.fromLTRB(0, 16, 0, 16),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Text(
                    "Bestellen",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                Container(
                  height: 50,
                  child: ListView(
                    controller: _scrollController,
                    shrinkWrap: false,
                    scrollDirection: Axis.horizontal,
                    children: <Widget>[
                      FlatButton(
                        onPressed: () => _tabController.animateTo(1),
                        child: Text(
                          "BRÖTCHEN",
                          style: TextStyle(
                              fontFamily: "Open Sans",
                              color: Colors.green[800],
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      ),
                      FlatButton(
                        onPressed: () => _tabController.animateTo(2),
                        child: Text(
                          "KALTGETRÄNKE",
                          style: TextStyle(
                              fontFamily: "Open Sans",
                              color: Colors.grey,
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      ),
                      FlatButton(
                        onPressed: () => _tabController.animateTo(3),
                        child: Text(
                          "HEIßGETRÄNKE",
                          style: TextStyle(
                              fontFamily: "Open Sans",
                              color: Colors.grey,
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      ),
                      FlatButton(
                        onPressed: () {},
                        child: Text(
                          "MILCHPRODUKTE",
                          style: TextStyle(
                              fontFamily: "Open Sans",
                              color: Colors.grey,
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(20, 20, 20, 30),
                    child: TabBarView(controller: _tabController, children: [
                      CategoryTab(catId: "1"),
                      CategoryTab(catId: "2"),
                      CategoryTab(catId: "3"),
                      CategoryTab(catId: "4"),
                    ]),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}

class CategoryTab extends StatelessWidget {
  final String catId;

  const CategoryTab({Key key, @required this.catId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: Firestore.instance
            .collection('items')
            .where('catid', isEqualTo: catId)
            .snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasData) {
            return GridView.builder(
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              shrinkWrap: true,
              itemCount: snapshot.data.documents.length,
              itemBuilder: (BuildContext context, int index) {
                return ItemCard(
                  cost: snapshot.data.documents[index]["cost"] == null
                      ? 1
                      : snapshot.data.documents[index]["cost"],
                  name: snapshot.data.documents[index]["name"],
                  desc: snapshot.data.documents[index]["desc"] == null
                      ? "Keine Beschreibung vorhanden"
                      : snapshot.data.documents[index]["desc"],
                  imageUrl: snapshot.data.documents[index]["image_path"],
                );
              },
            );
          } else {
            return Container(
                height: 50, width: 50, child: CircularProgressIndicator());
          }
        });
  }
}

Приложение: What I want

1 Ответ

0 голосов
/ 04 мая 2020

Проверьте это, это работает отлично: Проверьте код ниже:

import 'package:flutter/material.dart';

class MyTabBar extends StatefulWidget {
  @override
  _MyTabBarState createState() => _MyTabBarState();
}

class _MyTabBarState extends State<MyTabBar>
    with SingleTickerProviderStateMixin {
  // define your tab controller here
  TabController _tabController;

  @override
  void initState() {
    // initialise your tab controller here
    _tabController = TabController(length: 4, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Icon(
          Icons.menu,
          color: Colors.black,
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          'Aszeit eSG',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
            child: TabBar(
              controller: _tabController,
              labelColor: Colors.green,
              isScrollable: true,
              indicatorColor: Colors.transparent,
              unselectedLabelColor: Colors.grey,
              unselectedLabelStyle: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontWeight: FontWeight.w700,
              ),
              labelStyle: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w700,
              ),
              tabs: <Widget>[
                Text('BROTCHEN'),
                Text('KALTEGETRANKE'),
                Text('HEIBGETRANKE'),
                Text('MILCHPPODUKE'),
              ],
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: <Widget>[
                Center(
                  child: Text(
                    'BROTCHEN',
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),
                  ),
                ),
                Center(
                  child: Text(
                    'KALTEGETRANKE',
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),
                  ),
                ),
                Center(
                  child: Text(
                    'HEIBGETRANKE',
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),
                  ),
                ),
                Center(
                  child: Text(
                    'MILCHPPODUKE',
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Выход: enter image description here

enter image description here

...