Directive To Render Flutter Widget Role Based

Issue

I’m not sure how to implement directive in Flutter.

I have the following code in angular which creates directive to render element based on the role of user dynamicly. I want to implment in Fluter. How can I write in Flutter.

Directive Class

import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
import { AccountService } from '../../core/services/account.service';

@Directive({
  selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit{
  @Input() appHasRole: string[];

  constructor(private viewContainerRef: ViewContainerRef,
    private templateRef: TemplateRef<any>,
    private accountService: AccountService) {}

    ngOnInit(): void {
      const isAuthorized = this.accountService.isAuthorized('Role', this.appHasRole);
      if (!isAuthorized) {
        this.viewContainerRef.clear();
      } else {
        this.viewContainerRef.createEmbeddedView(this.templateRef);
      }
    }
}

How to use

  <a *appHasRole='["SuperAdmin","Admin"]' mat-list-item routerLink="users">
    View Users
  </a>

Solution

I have find workaround to create widget for wrapping.

import ‘package:flutter/material.dart’;
import ‘package:hybrid/services/account_service.dart’;

class AppHasRole extends StatelessWidget {
  final List<String> roles;
  final Widget child;

  final AccountService _accountService = AccountService();

  AppHasRole({
    Key? key,
    required this.roles,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _accountService.isAuthorized('Role', roles),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshop) {
        if (snapshop.hasData) {
          final bool isAuthorized = snapshop.data!;
          return isAuthorized ? child : Container();
        }
        return Container();
      },
    );
  }
}

Answered By – Sras

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *