TabBar控制器从另一个类更改页面

时间:2019-06-15 14:31:07

标签: flutter dart

我希望能够控制从另一个类在主页中查看的页面。  厌倦了使用全局键,但是它不接受将控制器发送给另一个类的方法,我创建了一个方法,并试图从第一类中控制它,但仍然无法正常工作,并且给了我这个错误

在处理手势时引发了以下NoSuchMethodError: I / flutter(16262):在null上调用了setter'index ='。 I /颤振(16262):接收器:空 I / flutter(16262):尝试调用:index = 1

这是我的家庭班

def rasa_agent():
    interpreter = RasaNLUInterpreter("Path for NLU")
    action_endpoint = EndpointConfig(url="Webhook URL")
    agent = Agent.load('Path to Dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
    ## Next line runs the rasa in commandline
    # rasa_core.run.serve_application(agent,channel='cmdline') 
    return agent

@app.route("/conversations/default/respond",methods=['POST'])
def run_weather_bot(serve_forever=True):

    agent = rasa_agent() # calling rasa agent
    ## Collect Query from POST request
    ## Send Query to Agent
    ## Get Response of BOT
    output = {} ## Append output
    return jsonify(output) 

这是我的第一堂课

import 'package:flutter/material.dart';
import 'package:flutter_tabs/first.dart';
import 'package:flutter_tabs/second.dart';
import 'package:flutter_tabs/third.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with SingleTickerProviderStateMixin {

  TabController controller;
  //var contKey=GlobalKey<TabBarView>();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar:AppBar(
        title: Text('hello'),
        bottom: TabBar(controller: controller,tabs: <Widget>[
          Tab(icon: Icon(Icons.ac_unit),),
          Tab(icon: Icon(Icons.library_books),)
        ]),
      ),
      body: TabBarView(controller: controller,children: <Widget>[
        First(),
        Second(),

      ]),
      floatingActionButton: FloatingActionButton(onPressed: ()=>controller.animateTo(controller.index =1)),

    );


  }


  void next(int num){
    debugPrint(num.toString());
      controller.animateTo(controller.index = num);


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

    controller =TabController(length: 2, vsync: this);
  }

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

这是我的第二堂课

import 'package:flutter/material.dart';
import 'package:flutter_tabs/Home.dart';
import 'package:flutter_tabs/second.dart';
class First extends StatefulWidget {
  @override
  _FirstState createState() => _FirstState();
}

class _FirstState extends State<First> {
Home home = Home();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: <Widget>[
            FlatButton(onPressed: ()=>debugPrint(''), child: Text('first')),
            FlatButton(onPressed: (){
              Home().createState().next(1);
            }, child: Text('click')),
          ],
        ),
      ),
    );
  }
}

解决此问题后我想要的是能够具有类别列表,并且当用户单击类别时,它会自动显示第二页以及该类别中的项目。

2 个答案:

答案 0 :(得分:0)

尝试一下。这实际上为我工作。找到了另一个堆栈溢出问题,但我实际上找不到它。因此,如果有人在此处添加它。

import 'package:flutter/material.dart';

class MainClass extends StatefulWidget {
  final Widget child;
  int initialPage; //this sets the innitial page to open when main class opens. ie if a main class is opened from secondpage and innitialPage is set to 1 then it will show the second page as the tabpages start from 0.

  MainClass({this.child,@required this.initialPage});

  @override
  _MainClassState createState() => _MainClassState();
}



class _MainClassState extends State<MainClass>
    with SingleTickerProviderStateMixin {
  TabController _tabController;


  @override
  void initState() {
    _tabController = TabController(vsync: this, length: 2, initialIndex: 0);

    super.initState();
  }

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

  //method to set the page. This method is very important.
  void _nextPage(int tab) {
    final int newTab = _tabController.index + tab;
    if (newTab < 0 || newTab >= _tabController.length) return;
    _tabController.animateTo(newTab);
  }

  @override
  Widget build(BuildContext context) {
    final Color color = Theme.of(context).primaryColor;
    return Scaffold(
      key: key,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        title: Text('TabBar Example'),
        centerTitle: true,
      ),
      bottomNavigationBar: TabBar(
        controller: _tabController,
        tabs: <Widget>[
          Tab(icon: Icon(Icons.home, Colors.blue)),
          Tab(icon: Icon(Icons.android, color: Colors.blue)),
        ],
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          //make sure the length is set to the number of pages. Also the tabs in the tabbar should be equal to no of pages.
          Center(child: Text("First Page")),//these are pages. You can add pages as your choice
          Center(child: Text("Second Page")),
          
        ],
      ),
    );
  }
}

如果要从另一个页面调用它。假设您要取消按钮的调用,对按钮的onpressed事件使用以下代码

Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) {
              return MainClass(initialPage: 1,); 

据此,它将返回主类的第二页,该主页包含制表符控制器,因为制表符从0开始。希望也对您有所帮助:-)

答案 1 :(得分:0)

Communication between widgets

本文回答了我的问题。 一切都与Tabs及其运作方式有关。