csells / go_router

The purpose of the go_router for Flutter is to use declarative routes to reduce complexity, regardless of the platform you're targeting (mobile, web, desktop), handling deep linking from Android, iOS and the web while still allowing an easy-to-use developer experience.
https://gorouter.dev
441 stars 96 forks source link

How to keep state in the "books" example #347

Closed amitrotner closed 2 years ago

amitrotner commented 2 years ago

Hi,

I am trying to add a state keeping ability to the "books" example. I have followed https://gorouter.dev/nested-navigation#keeping-state and changed author_list.dart so the authors list will be 50 times longer (just for the demonstration) and added AutomaticKeepAliveClientMixin.

// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:flutter/material.dart';

import '../data.dart';

class AuthorList extends StatefulWidget {
  const AuthorList({
    required this.authors,
    this.onTap,
    Key? key,
  }) : super(key: key);

  final List<Author> authors;
  final ValueChanged<Author>? onTap;

  @override
  State<AuthorList> createState() => _AuthorListState();
}

class _AuthorListState extends State<AuthorList> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView.builder(
      itemCount: widget.authors.length * 50,
      itemBuilder: (context, index) => ListTile(
        title: Text(
          widget.authors[index % widget.authors.length].name,
        ),
        subtitle: Text(
          '${widget.authors[index % widget.authors.length].books.length} books',
        ),
        onTap: widget.onTap != null ? () => widget.onTap!(widget.authors[index % widget.authors.length]) : null,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

However, when I scroll down the authors page, move to another page and return to the authors page, the state is not preserved.

How can I modify this example to enable state preserving?

Thanks

csells commented 2 years ago

Interesting. That sample worked when @rydmike built it. @rydmike thoughts about why it might not be working?