manan36chauhan / Topics-For-Flutter

only informative
0 stars 0 forks source link

dynamic tabbar firestore firbase example #4

Open manan36chauhan opened 1 year ago

manan36chauhan commented 1 year ago

Set up Firebase in your Flutter project by creating a Firebase project on the Firebase console, adding the necessary configuration files to your Flutter project, and adding the required dependencies in your pubspec.yaml file.

Create a new Flutter StatefulWidget and its accompanying State class.


class MyTabBarApp extends StatefulWidget {
  @override
  _MyTabBarAppState createState() => _MyTabBarAppState();
}

class _MyTabBarAppState extends State<MyTabBarApp> {
  // Add necessary variables and initialize them

  @override
  void initState() {
    super.initState();
    // Perform Firebase-related operations in the initState() method, such as authentication or data fetching
    // Update the necessary variables accordingly
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3, // Number of tabs
        child: Scaffold(
          appBar: AppBar(
            title: Text('My TabBar App'),
            bottom: TabBar(
              tabs: [
                Tab(text: 'Tab 1'),
                Tab(text: 'Tab 2'),
                Tab(text: 'Tab 3'),
              ],
            ),
          ),
          body: TabBarView(
            children: [
              // Content for Tab 1
              Container(
                child: Center(
                  child: Text('Tab 1 Content'),
                ),
              ),
              // Content for Tab 2
              Container(
                child: Center(
                  child: Text('Tab 2 Content'),
                ),
              ),
              // Content for Tab 3
              Container(
                child: Center(
                  child: Text('Tab 3 Content'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Inside the initState() method, you can perform Firebase-related operations such as authentication or fetching data from Firebase Firestore.


@override
void initState() {
  super.initState();
  // Perform Firebase-related operations, such as authentication or data fetching
  // For example, fetching data from Firebase Firestore
  FirebaseFirestore.instance
      .collection('your_collection')
      .get()
      .then((QuerySnapshot querySnapshot) {
    // Process the querySnapshot and update necessary variables accordingly
  })
  .catchError((error) {
    // Handle the error
  });
}

Update the content of each tab based on the Firebase data or state. For example, you can display data fetched from Firebase Firestore


TabBarView(
  children: [
    FutureBuilder(
      future: FirebaseFirestore.instance.collection('your_collection').get(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }
        return ListView(
          children: snapshot.data.docs.map((DocumentSnapshot document) {
            Map<String, dynamic> data = document.data() as Map<String, dynamic>;
            return ListTile(
              title: Text(data['title']),
              subtitle: Text(data['subtitle']),
            );
          }).toList(),
        );
      },
    ),
    // Content for other tabs
  ],
)

Remember to replace 'your_collection' with the actual name of your Firestore collection

Manan-dynamic commented 1 year ago
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        bottom: StreamBuilder<QuerySnapshot>(
          stream: FirebaseFirestore.instance.collection('myCollection').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (!snapshot.hasData) return const Text('Loading...');
            final tabs = snapshot.data.docs.map((doc) => Tab(text: doc['title'])).toList();
            _tabController = TabController(length: tabs.length, vsync: this);
            return TabBar(
              controller: _tabController,
              isScrollable: true,
              indicatorWeight: 0.1,
              indicatorPadding: EdgeInsets.all(0.0),
              indicatorColor: Colors.transparent,
              unselectedLabelColor: Colors.white,
              labelColor: Colors.orange,
              tabs: tabs,
            );
          },
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [],
      ),
    );
  }
}
Manan-dynamic commented 1 year ago
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:readmore/readmore.dart';
import 'package:vimeo_video_player/vimeo_video_player.dart';
import '../../globalinfo.dart';

class MyHomeTBPage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomeTBPage> with SingleTickerProviderStateMixin {
  CollectionReference _collectionRef = FirebaseFirestore.instance.collection('categories');
  List<Tab> tabsCategory = List();
  int _currentIndex = 0;

  final List<String> tabsText = ['Tab 1', 'Tab 2', 'Tab 3'];
  final List<String> _tabs = [];
  TabController _tabController;

  List<Tab> tabMaker() {
    List<Tab> tabs = List();
    for (var i = 0; i < tabsText.length; i++) {
      tabs.add(Tab(
        child: Text(
          tabsText[i],
          style: TextStyle(color: ColorTheme.Blue),
        ),
      ));

      tabsCategory.add(Tab(
        child: Text(
          tabsText[i],
          style: TextStyle(color: ColorTheme.Blue),
        ),
      ));
    };
    return tabs;
  }

  // final List<Widget> _children = [
  //   FirstPage(),
  //   SecondPage(),
  //   ThirdPage(),
  // ];

  getData1() {
    print("getData1 - Step1");
    // Get docs from collection reference
    _collectionRef.get().then((QuerySnapshot querySnapshot) {
      // Get data from docs and convert map to List
      final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
      allData.forEach((dynamic item) {
        _tabs.add(item['name']);
        tabsCategory.add(Tab(child: Text(item['name'],style: TextStyle(color: Colors.black),),));
      });
    }).catchError((error) {
      // Handle any errors that occur during the data retrieval
      print('Error fetching data: $error');
    });
  }

  Future<void> getData() async {
    // Get docs from collection reference
    print("data fetch----------");
    QuerySnapshot querySnapshot = await _collectionRef.get();

    // Get data from docs and convert map to List
    final allData = querySnapshot.docs.map((doc) => doc.data()).toList();

    // for (var i = 0; i < allData.length; i++) {
    //   //print('----------------'+allData[i]['categories'].toString());
    //   //tabs.add(Tab(child: Text(tabsText[i],style: TextStyle(color: ColorTheme.Blue),),));
    // };

    // FirebaseFirestore.instance.collection('categories').doc('type').get().then((doc) {
    //   if (doc.exists) {
    //     Map<String, dynamic> data = doc.data();
    //     print(data['myField']);
    //   } else {
    //     print('Document does not exist');
    //   }
    // });

    List<Tab> tabMaker() {
      List<Tab> tabs = List();

      allData.forEach((dynamic item) {
        // Perform operations with the item
        print("----------------------");
        print(item['name']);
        print(item.length);
        print("----------------------");
        print(allData.length);
        tabs.add(Tab(
          child: Text(
            item['name'],
            style: TextStyle(color: ColorTheme.Blue),
          ),
        ));
      });

      //for (var i = 0; i < tabsText.length; i++) {
      //  tabs.add(Tab(child: Text(tabsText[i],style: TextStyle(color: ColorTheme.Blue),),));
      //};
      return tabs;
    }

    //print(allData);
  }

  @override
  void initState() {
    super.initState();
    getData1();
    _tabController = TabController(length: _tabs.length, vsync: this);
  }

  // void functab(){
  //   FirebaseFirestore.instance.collection('categories').doc('title').snapshots().listen((DocumentSnapshot documentSnapshot) {
  //     List<dynamic> itemDetail = documentSnapshot['title'];
  //     print(itemDetail);
  //   });
  // }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
        appBar: TabBar(

          isScrollable: true,
          indicatorColor: Colors.black87,
          controller: _tabController,
          tabs: [
            for (final tab in _tabs)
              Tab(text: tab ,),
          ],
        ),
        body: TabBarView(
          controller: _tabController,

          children: [
            // FutureBuilder(
            //   future: FirebaseFirestore.instance.collection('categories').get(),
            //   builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            //     if (snapshot.hasError) {
            //       return Text('Error: ${snapshot.error}');
            //     }
            //     if (snapshot.connectionState == ConnectionState.waiting) {
            //       return CircularProgressIndicator();
            //     }
            //     return ListView(
            //       children: snapshot.data.docs.map((DocumentSnapshot document) {
            //         Map<String, dynamic> data = document.data() as Map<String, dynamic>;
            //         return ListTile(
            //           title: Text(data['name'].toString()),
            //           subtitle: Text(data['id'].toString()),
            //         );
            //       }).toList(),
            //     );
            //   },
            // ),
            // Content for other tabs

            // Content for Tab 1
            RefreshIndicator(
              onRefresh: (){
                Duration(seconds: 2);
              },
              child: Container(
                child: Center(
                  child: FutureBuilder(
                    future: FirebaseFirestore.instance.collection('videos').get(),
                    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                      if (snapshot.hasError) {
                        return Text('Error: ${snapshot.error}');
                      }
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return CircularProgressIndicator();
                      }
                      return ListView(
                        children: snapshot.data.docs.map((DocumentSnapshot document) {
                          Map<String, dynamic> data = document.data() as Map<String, dynamic>;
                          return Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Card(
                              child: Column(children: [
                                ClipRRect(
                                  borderRadius: BorderRadius.circular(15),
                                  child: VimeoVideoPlayer(
                                    autoPlay: false,
                                    url: data['vimeo_url'],
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(9.0),
                                  child: Text(
                                    data['title'],
                                    style: TextStyle(color: ColorTheme.Blue, fontSize: 15,fontWeight: FontWeight.bold),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(12.0),
                                  child: ReadMoreText(
                                    data['description']+'',
                                    trimLines: 2,
                                    colorClickableText: Colors.pink,
                                    trimMode: TrimMode.Line,
                                    trimCollapsedText: 'Show more',
                                    trimExpandedText: '...'+'Show less',
                                    moreStyle: TextStyle(fontSize: 14,color: Colors.pink),
                                    style: TextStyle(color: ColorTheme.Blue, fontSize: 15),
                                  ),
                                ),
                              ]),
                            ),
                          );
                          ListTile(
                            title: Text(data['title'].toString()),
                            subtitle: Text(data['id'].toString()),
                          );
                        }).toList(),
                      );
                    },
                  ),
                ),
              ),
            ),
            // Content for Tab 2
            Container(
              child: Center(
                child: FutureBuilder(
                  future: FirebaseFirestore.instance.collection('videos').get(),
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    }
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    }
                    return ListView(
                      children: snapshot.data.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data = document.data() as Map<String, dynamic>;
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Card(
                            child: Column(children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(15),
                                child: VimeoVideoPlayer(
                                  autoPlay: false,
                                  url: data['vimeo_url'],
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(9.0),
                                child: Text(
                                  data['title'],
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15,fontWeight: FontWeight.bold),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: ReadMoreText(
                                  data['description']+'',
                                  trimLines: 2,
                                  colorClickableText: Colors.pink,
                                  trimMode: TrimMode.Line,
                                  trimCollapsedText: 'Show more',
                                  trimExpandedText: '...'+'Show less',
                                  moreStyle: TextStyle(fontSize: 14,color: Colors.pink),
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15),
                                ),
                              ),
                            ]),
                          ),
                        );
                        ListTile(
                          title: Text(data['title'].toString()),
                          subtitle: Text(data['id'].toString()),
                        );
                      }).toList(),
                    );
                  },
                ),
              ),
            ),
            // Content for Tab 3
            Container(
              child: Center(
                child: Text('Branded Content'),
              ),
            ),
            // Content for Tab 4
            Container(
              child: Center(
                child: Text('Animation'),
              ),
            ),
            // Content for Tab 5
            Container(
              child: Center(
                child: Text('Sports'),
              ),
            ),
            // Content for Tab 6
            Container(
              child: Center(
                child: Text('Ads & Comercial'),
              ),
            ),
            // Content for Tab 7
            Container(
              child: Center(
                child: Text('Travel'),
              ),
            ),
            // Content for Tab 8
            Container(
              child: Center(
                child: Text('Documentry'),
              ),
            ),
            // Content for Tab 9
            Container(
              child: Center(
                child: Text('Music'),
              ),
            ),
            // Content for Tab 10
            Container(
              child: Center(
                child: Text('Comedy'),
              ),
            ),
          ],
          // children: [
          //   // for (final tab in _tabs)
          //   //   Center(child: Text(tab)),
          //
          // ],
        ),
      ),
    );
  }

}
Manan-dynamic commented 1 year ago

final code firestore


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:readmore/readmore.dart';
import 'package:vimeo_video_player/vimeo_video_player.dart';
import '../../globalinfo.dart';

class MyHomeTBPage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomeTBPage> with SingleTickerProviderStateMixin {
  CollectionReference _collectionRef = FirebaseFirestore.instance.collection('categories');
  //CollectionReference _collectionRef = FirebaseFirestore.instance.collection('categories').orderBy('sort',descending: false) as CollectionReference<dynamic>;
  List<Tab> tabsCategory = List();
  int _currentIndex = 0;

  final List<String> _tabs = [];
  //TabController _tabController;

  // final List<Widget> _children = [
  //   FirstPage(),
  //   SecondPage(),
  //   ThirdPage(),
  // ];

  getData1() {
    print("getData1 - Step1");
    // Get docs from collection reference
    _collectionRef.get().then((QuerySnapshot querySnapshot) {
      // Get data from docs and convert map to List
      final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
      allData.forEach((dynamic item) {
        _tabs.add(item['name']);
        tabsCategory.add(Tab(child: Text(item['name'],style: TextStyle(color: Colors.black),),));
      });
    }).catchError((error) {
      // Handle any errors that occur during the data retrieval
      print('Error fetching data: $error');
    });
  }

  @override
  void initState() {
    super.initState();
    getData1();
    //_tabController = TabController(length: _tabs.length, vsync: this);
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
      print(_currentIndex);
    });
  }

  // @override
  // void dispose() {
  //   _tabController.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
        appBar: TabBar(
          //onTap: onTabTapped,
          indicatorWeight: 4,
          indicatorColor: ColorTheme.Blue,
          isScrollable: true,
          //controller: _tabController,
          tabs: [
            for (final tab in _tabs)
              //Tab(text: tab.toString(),),
              Tab(child: Text(tab, style: TextStyle(color: ColorTheme.Blue, fontSize: 20))),
          ],
        ),
        body: TabBarView(

          //controller: _tabController,

          children: [
            // FutureBuilder(
            //   future: FirebaseFirestore.instance.collection('categories').get(),
            //   builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            //     if (snapshot.hasError) {
            //       return Text('Error: ${snapshot.error}');
            //     }
            //     if (snapshot.connectionState == ConnectionState.waiting) {
            //       return CircularProgressIndicator();
            //     }
            //     return ListView(
            //       children: snapshot.data.docs.map((DocumentSnapshot document) {
            //         Map<String, dynamic> data = document.data() as Map<String, dynamic>;
            //         return ListTile(
            //           title: Text(data['name'].toString()),
            //           subtitle: Text(data['id'].toString()),
            //         );
            //       }).toList(),
            //     );
            //   },
            // ),
            // Content for other tabs

            // Content for Tab 1

            ///1st container
            // Container(
            //   child: Center(
            //     child: Text('ALl'),
            //   ),
            // ),
            //

            ///All Container
            RefreshIndicator(
              onRefresh: (){
                Duration(seconds: 2);
              },
              child: Container(
                child: Center(
                  child: FutureBuilder(
                    future: FirebaseFirestore.instance.collection('videos').where('category_id',isEqualTo: 2).get(),
                    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                      if (snapshot.hasError) {
                        return Text('Error: ${snapshot.error}');
                      }
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return CircularProgressIndicator();
                      }
                      return ListView(
                        children: snapshot.data.docs.map((DocumentSnapshot document) {
                          Map<String, dynamic> data = document.data() as Map<String, dynamic>;
                          return Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Card(
                              child: Column(children: [

                                ClipRRect(
                                  borderRadius: BorderRadius.circular(15),
                                  child: VimeoVideoPlayer(
                                    autoPlay: false,
                                    url: data['vimeo_url'],
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(9.0),
                                  child: Text(
                                    data['title'],
                                    style: TextStyle(color: ColorTheme.Blue, fontSize: 15,fontWeight: FontWeight.bold),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(12.0),
                                  child: ReadMoreText(
                                    data['description']+'',
                                    trimLines: 2,
                                    colorClickableText: Colors.pink,
                                    trimMode: TrimMode.Line,
                                    trimCollapsedText: 'Show more',
                                    trimExpandedText: '...'+'Show less',
                                    moreStyle: TextStyle(fontSize: 14,color: Colors.pink),
                                    style: TextStyle(color: ColorTheme.Blue, fontSize: 15),
                                  ),
                                ),
                              ]),
                            ),
                          );
                          ListTile(
                            title: Text(data['title'].toString()),
                            subtitle: Text(data['id'].toString()),
                          );
                        }).toList(),
                      );
                    },
                  ),
                ),
              ),
            ),
            // Content for Tab 2
            ///Narrative
            Container(
              child: Center(
                child: FutureBuilder(
                  future: FirebaseFirestore.instance.collection('videos').get(),
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    }
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    }
                    return ListView(
                      children: snapshot.data.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data = document.data() as Map<String, dynamic>;
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Card(
                            child: Column(children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(15),
                                child: VimeoVideoPlayer(

                                  autoPlay: false,
                                  url: data['vimeo_url'],
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(9.0),
                                child: Text(
                                  data['title'],
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15,fontWeight: FontWeight.bold),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: ReadMoreText(
                                  data['description']+'',
                                  trimLines: 2,
                                  colorClickableText: Colors.pink,
                                  trimMode: TrimMode.Line,
                                  trimCollapsedText: 'Show more',
                                  trimExpandedText: '...'+'Show less',
                                  moreStyle: TextStyle(fontSize: 14,color: Colors.pink),
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15),
                                ),
                              ),
                            ]),
                          ),
                        );
                        ListTile(
                          title: Text(data['title'].toString()),
                          subtitle: Text(data['id'].toString()),
                        );
                      }).toList(),
                    );
                  },
                ),
              ),
            ),
            // Content for Tab 3
            Container(
              child: Center(
                child: FutureBuilder(
                  future: FirebaseFirestore.instance.collection('videos').get(),
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError) {
                      return Text('Error: ${snapshot.error}');
                    }
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    }
                    return ListView(
                      children: snapshot.data.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data = document.data() as Map<String, dynamic>;
                        return Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Card(
                            child: Column(children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(15),
                                child: VimeoVideoPlayer(

                                  autoPlay: false,
                                  url: data['vimeo_url'],
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(9.0),
                                child: Text(
                                  data['title'],
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15,fontWeight: FontWeight.bold),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.all(12.0),
                                child: ReadMoreText(
                                  data['description']+'',
                                  trimLines: 2,
                                  colorClickableText: Colors.pink,
                                  trimMode: TrimMode.Line,
                                  trimCollapsedText: 'Show more',
                                  trimExpandedText: '...'+'Show less',
                                  moreStyle: TextStyle(fontSize: 14,color: Colors.pink),
                                  style: TextStyle(color: ColorTheme.Blue, fontSize: 15),
                                ),
                              ),
                            ]),
                          ),
                        );
                        ListTile(
                          title: Text(data['title'].toString()),
                          subtitle: Text(data['id'].toString()),
                        );
                      }).toList(),
                    );
                  },
                ),
              ),
            ),
            // Content for Tab 4
            Container(
              child: Center(
                child: Text('Experimental'),
              ),
            ),
            // Content for Tab 5
            Container(
              child: Center(
                child: Text('Animation'),
              ),
            ),
            // Content for Tab 6
            Container(
              child: Center(
                child: Text('Sports'),
              ),
            ),
            // Content for Tab 7
            Container(
              child: Center(
                child: Text('Travel'),
              ),
            ),
            // Content for Tab 8
            Container(
              child: Center(
                child: Text('Ads & Comercial'),
              ),
            ),
            // Content for Tab 9

            Container(
              child: Center(
                child: Text('Documentry'),
              ),
            ),
            // Content for Tab 10
            Container(
              child: Center(
                child: Text('Music'),
              ),
            ),
            Container(
              child: Center(
                child: Text('Comedy'),
              ),
            ),

          ],

          // children: [
          //   for (final tab in _tabs)
          //     Center(child: Text(tab)),
          //
          // ],

        ),
      ),
    );
  }

}
Manan-dynamic commented 1 year ago

The number of tabs and TabBarView's children must be the same as DefaultTabController's length. one way of doing that is to have a map function that turns SubCategoryLoader into Tabs or pages:


  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: FirebaseDatabase.instance
          .reference()
          .child("SubCategoryNames")
          .once(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          if (snapshot.data != null) {
            return DefaultTabController(
                length: subCategoryLoaderList.length,
                child: Scaffold(
                  appBar: AppBar(
                    bottom: TabBar(
                      tabs: subCategoryLoaderList
                          .map((subCatagory) => Tab(text: subCatagory.Name))
                          .toList(),
                    ),
                  ),
                  body: TabBarView(
                    children: subCategoryLoaderList.map((sub){
                      return _buildList(key: "key${sub.id}", string: "some string");
                    }).toList(),
                  ),
                ));
          } else {
            return Loader();
          }
        } else {
          return Loader();
        }
      },
    );