Aditya Patnaik
Aditya Patnaik

Reputation: 1776

How to access widgets(not methods) defined in one class in other classes in dart

I am stuck in a problem where I need to access one of my custom widgets defined in one class in some other class.

I have tried making an object of that class(that has the custom widget) in my main class.

here's the error:

The method '_bottom' isn't defined for the class 'BottomBarApp'.\nTry correcting the name to the name of an existing method, or defining a method named '_bottom'.

class that has widget _bottom() that needs to be accessed in the main class.

class BottomBarApp extends StatefulWidget {
  @override
  _BottomBarAppState createState() => _BottomBarAppState();
}

class _BottomBarAppState extends State<BottomBarApp> {

 //widget to be accessed
  Widget _bottom()=> BottomNavigationBar(
    //somecode  
);


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _back,
      appBar: AppBar(
        backgroundColor: _back,
        title: Center(child:Text(_data)),
      ),
        body: Container(
          child: Center(
            child:  Text(_data,style: TextStyle(color: Colors.blue, fontSize: 40),),
          )

        ),


      bottomNavigationBar: object._bottom(),
    );


  }
}

main class

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);


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

class _MyHomePageState extends State<MyHomePage> {

 BottomBarApp object = new BottomBarApp(); //here's the object


  @override
  Widget build(BuildContext context) {
    return Scaffold(


     bottomNavigationBar: _bottom(),  //trying to access!!!!
    );
  }
}

Please Help!

Upvotes: 0

Views: 640

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277037

You cannot use methods to make reusable widgets.

If you need to instead extract that method into a class, and use that class directly.

Instead of:

class MyWidgetState extends State<MyWidget> {
  Widget someWidget() {
    return Container();
  }

  Widget build(BuildContext context) {
    return Container(child: someWidget());
  }
}

do:

class SomeWidget extends StatelessWidget {
  Widget build(BuildContext context) {
    return Container();
  }
}

class MyWidgetState extends State<MyWidget> {
  Widget build(BuildContext context) {
    return Container(child: SomeWidget());
  }
}

Upvotes: 1

Related Questions