'How to open the exact required screen of the flutter app from deep_link?

I'm using the uni_links package which creates a deep_link that when clicked opens exactly the screen I need. Now I am able to automatically open the app from the given link but it doesn't go to the exact screen I need, it just goes to the default page. I also use getX for state management if that helps. If the question is incorrect, please feel free to commend

The page needs to be opened from the link, new_password_page.dart

import 'package:darcy/app/global_widgets/base_button.dart';
import 'package:darcy/app/global_widgets/outline_textfield.dart';
import 'package:darcy/app/modules/forgot_password/forgot_controller_page.dart';
import 'package:darcy/routes/pages.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:uni_links/uni_links.dart';

import '../../../core/theme/app_theme.dart';

class NewPasswordPage extends StatelessWidget {
  final ForgotController _homeController = Get.find<ForgotController>();
  NewPasswordPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String newPassword = '';
    String confirmPassword = '';
    return Scaffold(
      backgroundColor: AppTheme.base_background,
      appBar: AppBar(
        title: Text('New Password'),
        elevation: 0.0,
        backgroundColor: AppTheme.transparent,
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.2,
                ),
                OutlinedTextField(
                  text: newPassword,
                  labelText: 'New password',
                  messageText: '',
                  onTextChange: (value) {
                    newPassword = value;
                  },
                  customIcon: Icons.password_rounded,
                  obscureText: true,
                ),
                const SizedBox(
                  height: 16.0,
                ),
                OutlinedTextField(
                  text: confirmPassword,
                  labelText: 'Confirm password',
                  messageText: '',
                  onTextChange: (value) {
                    confirmPassword = value;
                  },
                  customIcon: Icons.password_rounded,
                  obscureText: true,
                ),
                const SizedBox(
                  height: 32.0,
                ),
                SizedBox(
                    height: 40.0,
                    width: double.infinity,
                    child: BaseButton(
                      buttonText: 'confirm'.tr,
                      buttonColor: AppTheme.sign_in,
                      buttonFunction: () {
                        Get.toNamed(Routes.SUCCESS);
                      },
                    )),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

new_password_controller.dart

import 'dart:async';

import 'package:darcy/app/data/network/services/user_api.dart';
import 'package:darcy/core/base_controller/base_controller.dart';
import 'package:darcy/routes/pages.dart';
import 'package:flutter/services.dart';
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:get/get.dart';
import 'package:uni_links/uni_links.dart';

class ForgotController extends GetxController with BaseController {
  var id = '';
  var email = '';
  StreamSubscription? sub;

  final UserApi _userApi = Get.find<UserApi>();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    initUniLinks();
  }

  Future<Null> initUniLinks() async {
    try {
      String? initialLink = await getInitialLink();

      // Parse the link and warn the user, if it is not correct,
      // but keep in mind it could be `null`.
    } on PlatformException {
      // Handle exception by warning the user their action did not succeed
      // return?
    }
  }

  void forgot() async {
    showLoading(message: 'Please wait...', barrierDismissible: false);
    final Email send_email = Email(
      body: 'Đây nè em trai http://flutterbooksample.com',
      subject: 'Link khôi phụn password',
      recipients: ['[email protected]'],
      isHTML: false,
    );

    try {
      hideLoading();
      await FlutterEmailSender.send(send_email);
    } catch (e) {
      print("hàng: ${e}");
    }
    // await _userApi.forgot(email, int.parse(id)).then((value) {
    //   hideLoading();
    //   print(value.error);
    //   if (value.error != true) {
    //     Get.toNamed(Routes.RECOVERY);
    //   }
    // }).catchError((e) {
    //   handleErrorWithToast(e);
    // });
  }
}

method to open the app from link

Future<Null> initUniLinks() async {
    try {
      String? initialLink = await getInitialLink();

      // Parse the link and warn the user, if it is not correct,
      // but keep in mind it could be `null`.
    } on PlatformException {
      // Handle exception by warning the user their action did not succeed
      // return?
    }
  }

main.dart

import 'package:darcy/core/lang/localization_service.dart';
import 'package:darcy/core/storage/spref_helper.dart';
import 'package:darcy/core/theme/app_theme.dart';
import 'package:darcy/injector.dart';
import 'package:darcy/routes/pages.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  //forced portrait orientation only
  await InitialBinding().setup();
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]).then((_) {
    runApp(const MyApp());
  });
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Darcy',
      debugShowCheckedModeBanner: false,
      getPages: Pages.pages,
      initialRoute: Routes.SPLASH,
      initialBinding: InitialBinding(),
      theme: ThemeData(
        primarySwatch: AppTheme.colorPrimarySwatch,
      ),
      locale:
          Get.find<SharedPreferencesHelper>().getDefaultLocaleFromLangCode(),
      fallbackLocale: LocalizationService.fallbackLocale,
      translations: LocalizationService(),
    );
  }
}


Solution 1:[1]

I would suggest that you use named routes.

Let's say your deep link is something like https://my.app/new-password and you have a named route in your app for this page called new-password, then on your function initUnilinks, you get the path of the URI and navigate to the route you want.

Future<void> initUniLinks() async {
    try {
      Uri? initialLink = await getInitialLink();
      if (initalLink != null) {
        Navigator.of(context).pushNamed(initialLink.path);
      }
      
    } on PlatformException {
      // Handle exception by warning the user their action did not succeed
      // return?
    }
  }

I'm not familiar with getX, it might have something for routing that you could use.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lazaro Henrique