0

I am working with an application, which has to register the user, show all the registered users and be able to edit the user information.

The result I want to achieve is that when editing the user information, return to the list screen that it is rebuilt in its entirety and reload again all users but with the updated information.

Starting in the screen where the data listing is shown, I have my main view called AdministrativeListData, it is the view that is shown to the user, inside it I have a Widget AdministrativeListCard, the functionality of this is. When the user makes a scroll this same one calls again to the provider to be able to load the following users and to add them to the list.

Code AdministrativeListData:

 class AdministrativeListData extends StatefulWidget {
 @override
 _AdministrativeListDataState createState() => _AdministrativeListDataState();
}

class _AdministrativeListDataState extends State<AdministrativeListData> {
  @override
  Widget build(BuildContext context) {
final administrativeProvider = Provider.of<AdministrativeProvider>(context);

return Scaffold(
  appBar: AppBar(
      backgroundColor: ColorsTheme.primary,
      leading: GestureDetector(
        onTap: () {
          Navigator.pushReplacementNamed(context, 'home');
        },
        child: Container(
            padding: EdgeInsets.all(16),
            child: FaIcon(FontAwesomeIcons.arrowLeft)),
      ),
      actions: [
        InkWell(
          onTap: () {
            showSearch(
                context: context, delegate: AdministrativeDataSearch());
          },
          child: Padding(
            padding: EdgeInsets.all(16),
            child: FaIcon(FontAwesomeIcons.search),
          ),
        ),
      ],
      centerTitle: true,
      title: Text(Constants.titleAdministrativeRecordList),
      automaticallyImplyLeading: false),
  body: Stack(
    children: <Widget>[
      ImageBackground(),
      administrativeProvider.administrativeListPage.isEmpty
          ? CustomLoad()
          : Container(),
      AdministrativeListCard(
        listAdministrativeElement:
            administrativeProvider.administrativeListPage,
        onNextPage: () => administrativeProvider.getAdministratives(),
        ),
      ],
    ),
  );
 }
}

Code AdministrativeListCard:

    class AdministrativeListCard extends StatefulWidget {
        final List<DatumAdministrative> listAdministrativeElement;
        final Function onNextPage;

        AdministrativeListCard(
        {@required this.listAdministrativeElement, @required this.onNextPage});

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

class _AdministrativeListCardState extends State<AdministrativeListCard> {
  bool _canGetMore = true;
  final ScrollController _scrollController = ScrollController();
  final preferences = new PreferencesUser();

  @override
  Widget build(BuildContext context) {
    bool isScreenLarge = Screen.largeScreen(context);

    _scrollController.addListener(() {
      final double diff = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;

      if (diff <= 500) {
        if (_canGetMore) {
          _canGetMore = false;
          widget.onNextPage();
        }
      } else {
        _canGetMore = true;
      }
    });
    return Container(
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: isScreenLarge ? 3 : 2,
            crossAxisSpacing: 1,
            mainAxisSpacing: 1,
            childAspectRatio:
                isScreenLarge ? (220.0 / 220.0) : (200.0 / 200.0)),
        controller: _scrollController,
        itemCount: widget.listAdministrativeElement.length,
        itemBuilder: (context, i) => businessCardAdministrative(
            context, widget.listAdministrativeElement[i], isScreenLarge),
      ),
    );
  }

Inside AdministrativeListCard, to send the arguments to the screen where the data is edited, I send them as follows.

 Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => AdministrativeDetail(
              administrativeElement: administrativeElement)),
    ).then((value) => setState(() {})

Reading in groups, they commented that adding the then((value) => setState(() {}). That would make it update the whole view again, but that option didn't work for me.

To obtain the list of users, I do it like this:

  AdministrativeProvider() {
    this.getAdministratives();
  }

  getAdministratives() async {
    final token = await _secureStorage.readToken('token');
    _currentPage++;

    try {
      final headers = {
        'content-type': 'application/json',
        'accept': 'application/json',
        'authorization': 'Bearer $token'
      };

      final uri = Uri.parse(
          '${ApiPaths.basisApi}${ApiPaths.getEmployeesCount}?paginated=true&currentPage=$_currentPage&recordsPerPage=12');
      final response = await http.get(
        uri,
        headers: headers,
      );

      final administrative = Administrative.fromJson(response.body);

      administrativeListPage = [
        ...administrativeListPage,
        ...administrative.data
      ];
    } catch (exception, stackTrace) {
      await Sentry.captureException(
        exception,
        stackTrace: stackTrace,
      );
    }

    notifyListeners();
  }

1 Answer 1

0

First of all: are you sure you add the element to the list?

Also I suggest you to modify the code:

.then((value) {setState(() {}; print("Running then part...")})

Then in the class of _AdministrativeListCardState in the build/initState method add print("In _AdministrativeListCardState...");

Then check if the print("Running then part...") part runs before the print("In _AdministrativeListCardState...");

I suspect that your .then runs before you expect it...

When I needed something similar I did it like this:

await Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => AdministrativeDetail(
              administrativeElement: administrativeElement)),
    );

setState(() {});
2
  • Thank you very much for your input, yes you are right, going back again to AdministrativeListCard What is executed is .then Commented Aug 27, 2021 at 18:11
  • I made the adaptation to the example. But the tree update was not successful. Commented Aug 27, 2021 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.