toSegments method

void toSegments(
  1. List<String> segments, {
  2. Map<String, String> queryParameters = const {},
  3. String? hash,
  4. Map<String, String> historyState = const {},
  5. dynamic isReplacement = false,
})

Navigates to a new url based on path segments

For example: pushSegments('home', 'bob') ~ push('/home/bob')

The advantage of using this over push is that each segment gets encoded. For example: pushSegments('home', 'bob marley') ~ push('/home/bob%20marley')

hash will be added after a hash sign (#) in the url (this will not appear if empty)

queryParameters to add query parameters (you can also add them manually)

historyState is used an the web to restore browser history entry specific state (like scroll amount)

isReplacement determines whether to overwrite the current history entry or create a new one. The is mainly useful when using back, forward or historyGo, or on the web to control the browser history entries

Also see:

  • to if you don't need segment encoding
  • toNamed if you want to navigate by name
  • toExternal if you want to navigate to an external url

Implementation

void toSegments(
  List<String> segments, {
  Map<String, String> queryParameters = const {},
  String? hash,
  Map<String, String> historyState = const {},
  isReplacement = false,
}) {
  // Forming the new url by encoding each segment and placing "/" between them
  final newUrl =
      segments.map((segment) => Uri.encodeComponent(segment)).join('/');

  // Calling push with this newly formed url
  return to(
    '/$newUrl',
    queryParameters: queryParameters,
    hash: hash,
    historyState: historyState,
    isReplacement: isReplacement,
  );
}