在单独的BottomNotifcationBar类中使用setState返回主类

时间:2019-02-19 04:32:52

标签: dart flutter

如果我将bottomNotificationBar与页面的其余部分放在同一类中,则setState可以正常工作,而按钮也可以正常工作。

如果将bottomNotificationBar移到另一个类,则无法使setState工作,因为它需要引用回到主类。我已经尝试了一些方法,但是我还不能确定这一点。

错误是: 处理手势时引发了以下断言: 在构造函数中调用setState():

不起作用的部分标记在此底部附近:

<script src="https://npmcdn.com/parse/dist/parse.min.js"></script>
<script type="text/javascript">
    Parse.serverURL = "https://parseapi.back4app.com";
    Parse.initialize(
        "MY_APP_ID",
        "MY_JS_KEY"
    );
</script>

--------------编辑:----------------

好吧,现在我在下面有以下代码,并且得到了以下两点:

信息: 成员“ setState”只能在“ package:flutter / src / widgets / framework.dart”子类的实例成员内使用。

例外: 处理手势时引发了以下NoSuchMethodError: 方法“ setState”在null上被调用。 接收者:null 尝试调用:setState(Closure:()=> Null)

    import 'package:flutter/material.dart';

    void main() {
      runApp(new MyApp());
    }

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'My Title',
          home: new MyHomePage(),
        );
      }
    }


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


    class _MyHomePageState extends State<MyHomePage> {
      var selectedPageIndex = 0;
      var pages = [ Page1(), Page2(), ];

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          body: pages[selectedPageIndex],
          bottomNavigationBar:
              MyClass().buildBottomNavigationBar(selectedPageIndex),
        );
      }
    }

    class MyClass {
      BottomNavigationBar buildBottomNavigationBar(selectedPageIndex) {
        return new BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              title: Text("Page1"),
              icon: Icon(Icons.account_circle),
            ),
            BottomNavigationBarItem(
              title: Text("Page2"),
              icon: Icon(Icons.account_circle),
            ),
          ],
          onTap: (index) {

/////////////////////////////START OF SECTION///////////////////////////
            _MyHomePageState().setState(() {
              selectedPageIndex = index;
            });
/////////////////////////////END OF SECTION///////////////////////////

          },
          currentIndex: selectedPageIndex,
        );
      }
    }

2 个答案:

答案 0 :(得分:1)

您需要的是另一类的CallBAck函数。由于必须在对象-setState上调用_MyHomePageState

通过Class Constructors,我们传递了初始数据并在SetState()上获得了回叫。

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'My Title',
      home: new MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  var selectedPageIndex = 0;
  var pages = [
    Page1(),
    Page2(),
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: pages[selectedPageIndex],
      bottomNavigationBar: MyClass(
        selectedPageIndex: selectedPageIndex,
        myFunc: _myFunc,
      ),
    );
  }

  void _myFunc(int index) {
    setState(() {
      selectedPageIndex = index;
    });
  }
}

class MyClass extends StatelessWidget {
  MyClass({this.selectedPageIndex, this.myFunc});
  final int selectedPageIndex;
  final Function myFunc;
  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      items: [
        BottomNavigationBarItem(
          title: Text("Page1"),
          icon: Icon(Icons.account_circle),
        ),
        BottomNavigationBarItem(
          title: Text("Page2"),
          icon: Icon(Icons.account_circle),
        ),
      ],
      onTap: (index) {
/////////////////////////////START OF SECTION///////////////////////////
        myFunc(index);
/////////////////////////////END OF SECTION///////////////////////////
      },
      currentIndex: selectedPageIndex,
    );
  }
}

class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Text('1'),
      ),
    );
  }
}

class Page2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Container(child: Text('3'),));
  }
}

答案 1 :(得分:0)

您应该通过向其中添加MyHomePage方法来修改static,以便可以从任何地方调用其状态:

  class MyHomePage extends StatefulWidget {

  static void setIndex(BuildContext context, int _newIndex) {
  _MyHomePageState state = context.ancestorStateOfType(TypeMatcher<_MyHomePageState>());
    state.setState(() {
      state.selectedPageIndex =_newIndex;
    });
  }

  @override
  _MyHomePageState createState() => new _MyHomePageState();
  }

然后,当您想更改index调用时:

  onTap (index) {
    MyHomePage.setIndex(context, index);
  }