Factory in dart

56 Views Asked by At

i'm new in Dart. I came from Java and there someting I want to mimic. I have a project that has multiple screens and each screen has multiple bodies. For exemple: Screen UMW0001 Body: 0001 Body: 0002 Body: 0003

I want to build those widgets according to the body. I have a widget call BuildBody, today he's like this:

String body = autorization.getBody("UMW0001");

switch (body) {
  case '0002':
    return const detalhe_0002.Detalhe();
  default:
    return const detalhe_0001.Detalhe();
}

I would like to improve this by using some kind of factory to build the right body, something like

String body = "0002";

Widget widget = methodToCreateWidget("page/umw0001/$body");

return widget();

Is flutter capable of that?

1

There are 1 best solutions below

0
pixel On

You can do it with below code. Here i have taken the buildBody as an higher level function you can put it any class and make it static if you wish and can do in the constructor too.

class Detalhe0001 extends StatelessWidget {
  const Detalhe0001({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Detalhe 0001'),
    );
  }
}

class Detalhe0002 extends StatelessWidget {
  const Detalhe0002({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text('Detalhe 0002'),
    );
  }
}

void main() {
  String body = "0002";
  Widget widget = buildBody("page/umw0001/$body");

  runApp(
    MaterialApp(
      home: Scaffold(
        body: widget,
      ),
    ),
  );
}

Widget buildBody(String body) {
  switch (body.split('/').last) {
    case '0002':
      return const Detalhe0002();
    default:
      return const Detalhe0001();
  }
}

Let me know if you have any doubt regarding this.