Почему трепетание выдает недопустимые аргументы при получении дочерних элементов на основе индекса? - PullRequest
0 голосов
/ 25 апреля 2020

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

РАБОЧИЙ КОД :

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

class _HomeState extends State<Home> {
  int selectedIndex = 0;

  PageController controller = PageController();

  List<GButton> tabs = new List();

  final List<Widget> _children = [
    Settings(),
    ListFamily(),
    CameraScreen(),
    SplashAccount(),
    Questions()
  ];

  @override
  void initState() {
    super.initState();

    var padding = EdgeInsets.symmetric(horizontal: 18, vertical: 5);
    double gap = 10;

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.settings,
      // textStyle: t.textStyle,
      text: 'Settings',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.wc,
      // textStyle: t.textStyle,
      text: 'Relations',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.camera_alt,
      // textStyle: t.textStyle,
      text: 'Camera',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.video_library,
      // textStyle: t.textStyle,
      text: 'Videos',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.question_answer,
      // textStyle: t.textStyle,
      text: 'Questions',
    ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        extendBody: true,
        body: PageView.builder(
          onPageChanged: (page) {
            setState(() {
              selectedIndex = page;
            });
          },
          controller: controller,
          itemBuilder: (context, position) {
            return Column(
              children: <Widget>[
                Expanded(child: _children[position]),
                Container(
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(12),
                          topRight: Radius.circular(12),
                          bottomLeft: Radius.zero,
                          bottomRight: Radius.zero),
                      boxShadow: [
                        BoxShadow(
                            spreadRadius: -10,
                            blurRadius: 60,
                            color: Colors.black.withOpacity(.20),
                            offset: Offset(0, 15))
                      ]),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 20),
                    child: GNav(
                        tabs: tabs,
                        selectedIndex: selectedIndex,
                        onTabChange: (index) {
                          print(index);
                          setState(() {
                            selectedIndex = index;
                          });
                        }),
                  ),
                ),
              ],
            );
          },
          itemCount: tabs.length, // Can be null
        ),
      ),
    );
  }
}

Неверный код аргумента (ов) :

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

class _HomeState extends State<Home> {
  int selectedIndex = 0;

  PageController controller = PageController();

  List<GButton> tabs = new List();

  final List<Widget> _children = [
    Settings(),
    Container(),
    Container(),
    Container(),
    Container()
  ];

  @override
  void initState() {
    super.initState();

    var padding = EdgeInsets.symmetric(horizontal: 18, vertical: 5);
    double gap = 10;

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.settings,
      // textStyle: t.textStyle,
      text: 'Settings',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.wc,
      // textStyle: t.textStyle,
      text: 'Relations',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.camera_alt,
      // textStyle: t.textStyle,
      text: 'Camera',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.video_library,
      // textStyle: t.textStyle,
      text: 'Videos',
    ));

    tabs.add(GButton(
      gap: gap,
      iconActiveColor: maincolor,
      iconColor: Colors.grey,
      textColor: maincolor,
      iconSize: 24,
      padding: padding,
      icon: Icons.question_answer,
      // textStyle: t.textStyle,
      text: 'Questions',
    ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            extendBody: true,
            body: Column(
              children: <Widget>[
// _children[selectedIndex] will cause the Invalid Argument(s) error here.
                Expanded(child: _children[selectedIndex]),
                Container(
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(12),
                          topRight: Radius.circular(12),
                          bottomLeft: Radius.zero,
                          bottomRight: Radius.zero),
                      boxShadow: [
                        BoxShadow(
                            spreadRadius: -10,
                            blurRadius: 60,
                            color: Colors.black.withOpacity(.20),
                            offset: Offset(0, 15))
                      ]),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 20),
                    child: GNav(
                        tabs: tabs,
                        selectedIndex: selectedIndex,
                        onTabChange: (index) {
                          print(index);
                          setState(() {
                            selectedIndex = index;
                          });
                        }),
                  ),
                ),
              ],
            )));
  }
}

В настоящее время я использую только библиотеку материалов Flutter и этот плагин: https://github.com/sooxt98/google_nav_bar

Кроме того, я пробовал это с другими нижними панелями навигации, как ну, я просто озадачен, почему это происходит

Дети в рабочем коде - мои другие страницы. Код страницы настроек ниже:

class Settings extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<Settings> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              // Logo + Container
              Container(
                color: thirdcolor,
                child: Center(
                  child: SafeArea(
                    child: Container(
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage(
                                  "assets/mvvdesign/Solid/White/horizontal/logo.png"),
                              fit: BoxFit.fitWidth)),
                    ),
                  ),
                ),
              ),
              // Container for Questions bar

              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            "SETTINGS",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: fontsize,
                                fontFamily: fontfamily,
                                fontWeight: FontWeight.w300),
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 10.0),
                            color: Colors.white,
                            child: Divider(
                              height: 5.0,
                              thickness: 3.0,
                              endIndent: 100.0,
                              indent: 100.0,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              Container(
                margin: const EdgeInsets.only(top: 20.0),
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 60,
                      width: MediaQuery.of(context).size.width - 50,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15.0),
                          border: Border.all(color: Colors.white, width: 2.0)),
                      child: Center(
                        child: SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                "Hey, ",
                                style: TextStyle(
                                  fontSize: 24.0,
                                  color: Colors.white,
                                ),
                              ),
                              Text(
                                "Alyssa Thurman",
                                style: TextStyle(
                                    fontSize: 24.0,
                                    color: Colors.green,
                                    fontWeight: FontWeight.bold),
                              ),
                            ],
                          ),
                        ),
                      ),
                      margin: const EdgeInsets.only(bottom: 10.0),
                    ),
                  ],
                ),
              ),

              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        width: 360.0,
                        height: 56.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.white),
                        margin: const EdgeInsets.only(top: 20.0),
                        child: Center(
                            child: Text(
                          "Update Account Information",
                          style: TextStyle(fontSize: 24.0, color: maincolor),
                        )),
                      ),
                      Container(
                        width: 360.0,
                        height: 56.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.white),
                        margin: const EdgeInsets.only(top: 40.0),
                        child: Center(
                            child: Text(
                          "Terms and Conditions",
                          style: TextStyle(fontSize: 24.0, color: maincolor),
                        )),
                      ),
                      Container(
                        width: 360.0,
                        height: 56.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.white),
                        margin: const EdgeInsets.only(top: 40.0),
                        child: Center(
                            child: Text(
                          "Privacy Policy",
                          style: TextStyle(fontSize: 24.0, color: maincolor),
                        )),
                      ),
                      Container(
                        width: 360.0,
                        height: 56.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.white),
                        margin: const EdgeInsets.only(top: 40.0),
                        child: Center(
                            child: Text(
                          "Manage Membership",
                          style: TextStyle(fontSize: 24.0, color: maincolor),
                        )),
                      ),
                      Container(
                        width: 360.0,
                        height: 56.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.0),
                            color: Colors.red),
                        margin: const EdgeInsets.only(top: 40.0, bottom: 40.0),
                        child: InkWell(
                          onTap: () async {
                            await OneSignal.shared.logoutEmail();
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.remove('accesstoken');
                            prefs.remove('refreshtoken');
                            prefs.remove('email');
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => First()),
                            );
                          },
                          child: Center(
                              child: Text(
                            "LOGOUT",
                            style:
                                TextStyle(fontSize: 24.0, color: Colors.white),
                          )),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
      resizeToAvoidBottomPadding: false,
      backgroundColor: thirdcolor,
    );
  }
}

Журнал ошибок: https://pastebin.com/raw/Regkgcqk

1 Ответ

0 голосов
/ 25 апреля 2020

РЕДАКТИРОВАТЬ : Я понял, почему это не работает (довольно точно). У меня есть функция, которая захватывает сохраненное значение индекса из постоянного хранилища и устанавливает selectedIndex на это значение при инициализации состояния.

Однако, когда сохраненный индекс захватывается, он возвращает ноль (потому что он не был установить еще) значение. Поэтому он передает это нулевое значение в selectedIndex, а затем и в конструктор; приводя к ошибке неверного аргумента (-ов), поскольку индекс не может быть нулевым.

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

Альтернативное решение :

Используйте построитель просмотра страниц и задайте свойства по своим предпочтениям.

Мои предпочтения: Внутри PageView.builder ()

physics: NeverScrollableScrollPhysics()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...