Home > Mobile >  Custom Scaffold class not draw the AppBar
Custom Scaffold class not draw the AppBar

Time:12-16

I'm trying to create a custom Scaffold extending the original class. With a default AppBar if not passed a new one.

class CommonScaffold extends Scaffold {
  final AppBar? appBar;
  final Widget body;

  CommonScaffold({
    Key? key,
    this.appBar,
    required this.body,
  }) : super(
    key: key,
    body: body,
    appBar: appBar ??
        AppBar(
          title: const Text("Default Text"),
        ),
  );
}

If I call the class avoiding pass the appBar parameter the AppBar will not appear. But should appear.

@override
  Widget build(BuildContext context) {
    return CommonScaffold(
      body: _createContent(),
    );
  }

If I call the class passing an AppBar to the appBar parameter the AppBar will appear.

@override
  Widget build(BuildContext context) {
    return CommonScaffold(
      body: _createContent(),
      appBar: AppBar(
          title: const Text("TEST"),
      ),
    );
  }

CodePudding user response:

The issue is here we are having two appBar and body for CommonScaffold. First set is coming because of extends Scaffold and second set is by declaring two on CommonScaffold.

You can check how it works on OOP by running this snippet. On dartPad. I'm changing names for better understanding the concept.

class Super {
  final int? a;
  final int? b;

  const Super({this.a, this.b});
}

class Common extends Super {
  final int? ca;
  final int b;

  const Common({this.ca, required this.b}) : super(a: ca ?? 10, b: b);
}

void main() {
  final c = Common(b: 1);
  print("supper a: ${c.a}"); // 10:  will refer supper class 
  print("Common a: ${c.ca}"); // null:  will refer common class 
}

Now for your answer, It will be better to change attributes name of CommonScaffold to avoid conflicting with super class.

Here is the answer on dartPad


class CommonScaffold extends Scaffold {
  final AppBar? cAppBar;

  final Widget? cBody;

  CommonScaffold({
    Key? key,
    this.cAppBar,
    this.cBody,
  }) : super(
            key: key,
            body: cBody,
            appBar: cAppBar ??
                AppBar(
                  title: Text("Default Appbar"),
                ));
}

class A extends StatelessWidget {
  const A({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      cBody: Text("body"),
    );
  }
}

CodePudding user response:

if you only want to show or not the appBar you can use this example by modifying the value of the bool to show or not the bar

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: (showAppbar)? AppBar(
          title: const Text("Default Text"),
        ): AppBar(
          title: const Text("TEST"),
      ),
      body: Center(
        child: Text(
          'Hello, a!',
        ),
      ),
    );
  }
  • Related