【问题标题】:Problem in TabBar Controller (no tabBar controller for tabBar)TabBar 控制器中的问题(tabBar 没有 tabBar 控制器)
【发布时间】:2020-09-24 18:46:39
【问题描述】:

所以我正在尝试创建一个包含 3 个选项卡的个人资料屏幕...个人资料、最近的和审查但是在尝试这样做时我遇到了一个错误。我无法代表所有 3 个选项卡。最近的标签有这个小部件。我已经用完了字符因此这里有一个完整代码的链接:https://docs.google.com/document/d/1qs4ajPJ0DBjserBJ3iBZmPXPz1zTP7tIYSh8vceVQn8/edit?usp=sharing

import 'package:econoomaccess/UpdateMapPage.dart';
import 'package:econoomaccess/drawer.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'localization/language_constants.dart';
import 'main.dart';
import 'localization/language.dart';
import 'package:flutter/cupertino.dart';

class UserProfilePage extends StatefulWidget {
  final Map map;
  UserProfilePage({this.map});
  @override
  _UserProfilePageState createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  Firestore firestore = Firestore.instance;
  var _name, _uid, _phone, _language, _location, _image, menuType = "profile";
  Language language;
  void _changeLanguage(Language language) async {
    Locale _locale = await setLocale(language.languageCode);
    MyApp.setLocale(context, _locale);
  }

  void getData() async {
    var temp;
    _auth.onAuthStateChanged.listen((user) async {
      temp = await firestore.collection('users').document(user.uid).get();
      setState(() {
        _uid = user.uid;
        _name = temp.data['name'];
        _phone = temp.data['mobileno'];
        _image = temp.data['image'];
        _language = temp.data['language'];
        _location = temp.data['city'];
      });
    });
  }

//PS THERE'S A LOT MORE CODE WHICH WAS IRRELEVANT TO THE CONTEXT OF QUES HENCE //I'VE DELETED IT
  TabController tabController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: Padding(
          padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
          child: SizedBox(
            height: 54,
            child: BottomNavigationBar(
              showSelectedLabels: false,
              showUnselectedLabels: false,
              backgroundColor: Color.fromRGBO(255, 255, 255, 0.8),
              currentIndex: _selectedIndex,
              selectedItemColor: Color(0xffFE506D),
              onTap: _onItemTapped,
              items: [
                BottomNavigationBarItem(
                  icon: Icon(
                    Icons.explore,
                    color: Colors.black,
                  ),
                  title: Text("Explore"),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.search, color: Colors.black),
                  title: Text("Search"),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.bookmark_border, color: Colors.black),
                  title: Text("Faavorites"),
                ),
                BottomNavigationBarItem(
                  icon: Icon(Icons.perm_identity, color: Color(0xffFE506D)),
                  title: Text("Shop"),
                )
              ],
            ),
          )),
      drawer: DrawerWidget(uid: this.uid),
      appBar: AppBar(
        backgroundColor: Colors.white,
        iconTheme: IconThemeData(color: Colors.black),
        elevation: 0,
      ),
      backgroundColor: Color(0xffE5E5E5),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Column(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.only(
                      bottomRight: Radius.circular(25),
                      bottomLeft: Radius.circular(25)),
                  child: Container(
                    height: 230,
                    width: MediaQuery.of(context).size.width,
                    decoration: new BoxDecoration(
                      // border: new Border.all(width: 1.0, color: Colors.black),
                      shape: BoxShape.rectangle,
                      color: Colors.white,
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                          color: Colors.black,
                          offset: Offset(20.0, 30.0),
                          blurRadius: 40.0,
                        ),
                      ],
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                            width: 155,
                            height: 155,
                            decoration: new BoxDecoration(
                                shape: BoxShape.circle,
                                image: new DecorationImage(
                                    fit: BoxFit.cover,
                                    image: new NetworkImage("$_image")))),
                        SizedBox(height: 10),
                        Text("$_name",
                            style: TextStyle(
                                fontSize: 25, fontWeight: FontWeight.bold))
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 15.0),
                      child: Container(
                        // margin: EdgeInsets.only(left: 15.0),
                        child: TabBar(
                          labelPadding: EdgeInsets.only(right: 30.0),
                          indicatorColor: Colors.transparent,
                          controller: tabController,
                          labelColor: Colors.black,
                          unselectedLabelColor: Colors.black26,
                          labelStyle: TextStyle(fontSize: 18,fontFamily: "Gilroy"),
                          unselectedLabelStyle: TextStyle(fontSize: 15,fontFamily: "Gilroy"),
                          isScrollable: true,
                          tabs: [
                            Tab(
                              text: getTranslated(context, "profile"),
                            ),
                            Tab(
                              text: getTranslated(context, "reviews"),
                            ),
                            Tab(
                              text: getTranslated(context, "recent"),
                            ),
                          ]
                        )
                      ),
                  ),
                ),
                Expanded(
                    child: TabBarView(
                        controller: tabController,
                        children: [
                          ProfileItems(), ReviewItems(), RecentItems()
                        ]
                    )
                )
              ],
            ),
          )
        ],
      )
    );
  }
}


我无法显示这 3 个标签。我面临的错误是 No TabController for TabBar,ERROR Message

The following assertion was thrown building Container:
No TabController for TabBar.

In this case, there was neither an explicit controller nor a default controller.
The relevant error-causing widget was: 
Container file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:658:30

(2) Exception caught by widgets library ═══════════════════════════════════════════════════
No TabController for TabBarView.
The relevant error-causing widget was: 
Expanded file:///C:/Flutter/Naniz_eats/lib/UserProfilePage.dart:684:17

【问题讨论】:

    标签: android-studio flutter dart flutter-layout flutter-dependencies


    【解决方案1】:

    您必须在有状态小部件的initState 方法中初始化tabController。检查下面的代码:

    // 创建一个 TabController 的实例 TabController tabController;

      void initState() {
        // TODO: implement initState
        // initialise the tab controller here
        tabController = TabController(vsync: this, length: 3);
        super.initState();
        getUser();
        getData();
      }
    
    

    同时将mixin 添加到您的有状态小部件。检查下面的代码:

    class _UserProfilePageState extends State&lt;UserProfilePage&gt; with SingleTickerProviderStateMixin{}

    【讨论】:

    • 感谢您的解决方案,但有一个小问题...编译器无法识别 tabController 出现错误。它显示错误:未定义名称'tabController'。
    • 您必须在初始化 TabController 之前创建一个实例,就像您在代码中所做的那样。检查我更新的答案@AdityaPandey
    【解决方案2】:

    您是否尝试过初始化 tabController 实例:

    tabController = TabController(vsync: this, length: 3);
    

    如果不这样做,您还必须使用SigleTickerProviderStateMixin

    class _TabbedPageState extends State<TabbedPage> with SingleTickerProviderStateMixin
    

    【讨论】:

    • 我试过像这样初始化tabController tabController = TabController;
    • 我是否必须创建另一个类_TabbedPageState
    • 不,这不是 dart 中的初始化工作方式。 TabController 是一个类型(类),你需要的是一个对象。如果这没有多大意义,那么您必须先阅读有关面向对象编程(类和对象)的内容。另外,请上传完整的小部件代码/文件
    • 这里是完整代码的链接:docs.google.com/document/d/…
    • 请编辑您的原始答案以包含请求的代码,以便其他人也可以查看。此外,在提出未来问题之前,请参阅本指南 - stackoverflow.com/help/how-to-ask
    【解决方案3】:

    所以这个问题的答案。在@T.T Sage 的帮助下,首先我必须使用 SingleTickerProviderStateMixin 扩展 userProfilePage 类 像这样:

    class _UserProfilePageState extends State<UserProfilePage> with SingleTickerProviderStateMixin
    

    然后用 DefaultTabController 包裹 Scaffold 以记住从 Tab Widget 中删除 tabcontroller 属性:

     Widget build(BuildContext context) {
        return DefaultTabController(
            length: 3,
            child: Scaffold(...)
       )
    }
    
    

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 2011-01-04
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多