android – Flutter GoRouter doesn’t render when reopening the app

android – Flutter GoRouter doesn’t render when reopening the app


I am coping with the next drawback:

When utilizing the app usually, if I press the again button whereas on the foundation route (/), the app closes. To this point, this conduct is ok and works as anticipated. Nevertheless, after I reopen the app, nothing renders. Though the weather are there (since I can work together with buttons by touching the display),however they aren’t seen.

flutter physician

[√] Flutter (Channel secure, 3.19.0, on Microsoft Home windows [Version 10.0.22631.4602], locale en-US)
[√] Home windows Model (Put in model of Home windows is model 10 or increased)
[√] Android toolchain - develop for Android units (Android SDK model 35.0.0)
[√] Chrome - develop for the online
[√] Visible Studio - develop Home windows apps (Visible Studio Neighborhood 2022 17.11.4)
[√] Android Studio (model 2024.1)
[√] VS Code (model 1.96.2)
[√] Linked system (4 out there)
[√] Community sources

app_routes.dart

import 'bundle:flutter_riverpod/flutter_riverpod.dart';
import 'bundle:go_router/go_router.dart';

import '../../pages/pages.dart';

remaining appRouterProvider = Supplier((ref) {
  return GoRouter(
    initialLocation: "https://stackoverflow.com/",
    routes: [
      GoRoute(
        path: "https://stackoverflow.com/",
        builder: (context, state) => const HomePage(),
        routes: [
          GoRoute(
            path: 'new-game',
            builder: (context, state) => const NewGamePage(),
          )
        ],
      ),
    ],
  );
});

essential.dart

import 'bundle:flag_game/dependecies.dart';
// import 'bundle:flag_game/pages/pages.dart';
import 'bundle:flutter/materials.dart';
import 'bundle:flutter_dotenv/flutter_dotenv.dart';
import 'bundle:flutter_riverpod/flutter_riverpod.dart';

import 'config/routes/route.dart';

Future essential() async {
  WidgetsFlutterBinding.ensureInitialized();
  const config = String.fromEnvironment('config');
  String fileName=".env";
  if (config.isNotEmpty) {
    fileName="$fileName.$config";
  }
  await dotenv.load(fileName: 'env/$fileName');

  dependecies();

  runApp(const ProviderScope(youngster: App()));
}

class App extends ConsumerWidget {
  const App({tremendous.key});

  @override
  Widget construct(BuildContext context, WidgetRef ref) {
    remaining appRouter = ref.watch(appRouterProvider);
    return MaterialApp.router(
      title: 'Flag Recreation',
      routerConfig: appRouter,
      restorationScopeId: 'app',
      // builder: (context, route) => Scaffold(
      //   physique: route,
      // ),
    );
  }
}

home_page.dart

// import 'bundle:flag_game/pages/pages.dart';
import 'bundle:flutter/materials.dart';
import 'bundle:flutter_animate/flutter_animate.dart';
import 'bundle:flutter_riverpod/flutter_riverpod.dart';
import 'bundle:go_router/go_router.dart';
import 'bundle:shared_preferences/shared_preferences.dart';

// import '../config/routes/route.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({tremendous.key});

  @override
  ConsumerState createState() => _HomePageState();
}

class _HomePageState extends ConsumerState {
  int bestScore = 0;
  @override
  void initState() {
    tremendous.initState();
    getBestScore();
  }

  Future sharedPreferences() async {
    return await SharedPreferences.getInstance();
  }

  Future getBestScore() async {
    remaining prefs = await sharedPreferences();
    var rating = prefs.getInt("bestScore") ?? 0;
    setState(() {
      bestScore = rating;
    });
  }

  @override
  Widget construct(BuildContext context) {
    Widget title = Textual content(
      'Mejor puntaje: $bestScore',
      model: const TextStyle(
        fontWeight: FontWeight.w900,
        fontSize: 40,
        shade: Colour(0xFF666870),
        top: 0.9,
        letterSpacing: -2,
      ),
    );
    title = title
        .animate(onPlay: (controller) => controller.repeat(reverse: true))
        .saturate(delay: 500.milliseconds, period: 500.milliseconds)
        .then() // set baseline time to earlier impact's finish time
        // .tint(shade: const Colour(0xFF80DDFF))
        .then()
        .blurXY(finish: 1)
        .fadeOut();

    return Scaffold(
      physique: Middle(
          youngster: Column(
        mainAxisAlignment: MainAxisAlignment.heart,
        kids: [
          title,
          Padding(
            padding: const EdgeInsets.only(top: 20),
            child: ElevatedButton(
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStatePropertyAll(Colors.grey[300])),
                onPressed: () {
                  context.push('/new-game');
                },
                youngster: const Textual content(
                  "Juego Nuevo",
                  model: TextStyle(shade: Colours.black),
                )),
          ),
        ],
      )),
    );
  }
}

new_game_page.dart

import 'bundle:knowledge/knowledge.dart';
import 'bundle:flutter/materials.dart';
import 'bundle:flutter_riverpod/flutter_riverpod.dart';

import 'bundle:font_awesome_flutter/font_awesome_flutter.dart';
import 'bundle:go_router/go_router.dart';
import 'bundle:shared_preferences/shared_preferences.dart';

import '../../companies/companies.dart';

class NewGamePage extends ConsumerStatefulWidget {
  const NewGamePage({tremendous.key});

  @override
  ConsumerState createState() => _NewGamePageState();
}

class _NewGamePageState extends ConsumerState {
  GameService gameService = GameService();
  bool disableButtons = false;
  bool loadingImg = false;
  int bestScoreLocal = 0;
  int bestScoreGlobal = 0;
  int lives = 0;
  QuestionResponseModel questionResponse = QuestionResponseModel();

  @override
  void initState() {
    tremendous.initState();
    newGame();
  }

  Future sharedPreferences() async {
    return await SharedPreferences.getInstance();
  }

  void newGame() {
    setupGame();
    newQuestion();
    getBestScore();
  }

  void setupGame() {
    setState(() {
      lives = 5;
    });
  }

  void gameOver() {
    context.pop();
  }

  void newQuestion() async {
    remaining r = await gameService.newQuestion(QuestionParamsModel());
    setState(() {
      questionResponse = r;
      disableButtons = false;
    });
  }

  void validateAnswer(CountryItemModel el) {
    loadingImg = true;
    bool isGameOver = false;
    setState(() {
      disableButtons = true;
    });
    String msg = "Correcto";
    String gameOverText = "Juego Terminado";
    String correctAnsw = '';
    bool isCorrect = el.id == questionResponse.correctAnswer?.id;
    if (!isCorrect) {
      msg = "Incorrecto";
      correctAnsw = questionResponse.correctAnswer!.countryName;
      lives -= 1;
    } else {
      setState(() {
        bestScoreLocal += 1;
      });
    }
    isGameOver = lives == 0;
    if (isGameOver) {
      setBestScore();
    }
    showModalBottomSheet(
      useSafeArea: true,
      isDismissible: false,
      barrierColor: Colours.clear,
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(10),
          top: 230,
          youngster:Placeholder(),
        );
      },
    );
  }

  Future setBestScore() async {
    remaining prefs = await sharedPreferences();
    var rating = prefs.getInt('bestScore') ?? 0;
    if (bestScoreLocal > rating) {
      prefs.setInt('bestScore', bestScoreLocal);
    }
  }

  Future getBestScore() async {
    remaining prefs = await sharedPreferences();
    var rating = prefs.getInt('bestScore') ?? 0;
    setState(() {
      bestScoreGlobal = rating;
    });
  }

  @override
  Widget construct(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colours.greenAccent,
          title: const Middle(youngster: Textual content("Adivina la Bandera")),
        ),
        physique: Container(
          padding: const EdgeInsets.all(10),
          youngster: Placeholder(),
        ));
  }
}

As proven within the video, after I press the again button to shut the app, every thing appears high quality. Nevertheless, upon reopening, no components render on the display. When you take a look at the VS Code console, the app does not really terminate its execution, however I am unable to work out what’s inflicting the issue.

Does anybody have an concept what could be going flawed?

I’ve tried including restorationScopeId: 'app', however it’s in useless. I modified the configuration in the primary file by commenting out the builder part, nevertheless it does not work.

Leave a Reply

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