Search code examples
flutterdartruntime-erroruristring-parsing

error "Unsupported operation: removeLast" from List<String> generated by Uri.parse('').pathSegments


running the code below on dartpad currently Based on Flutter 1.23.0-18.1.pre Dart SDK 2.10.4

import 'package:flutter/material.dart';

void main() {
  final _list = ['1', '2', '3', '4'];
  print('_list is a ${_list.runtimeType}');

  print('${_list.last}');

  try {
    _list.removeLast();
  } catch (e) {
    print(e);
  }

  print('${_list.last}');
  
  final _routeInfo = RouteInformation(location: '/user/info/5');
  final _segments = Uri.parse(_routeInfo.location).pathSegments;

  print('_segments is a ${_segments.runtimeType}');

  print('${_segments.last}');

  try {
    _segments.removeLast();
  } catch (e) {
    print(e);
  }

  print('${_segments.last}');
}

I have this output below:

_list is a List<String>
4
3
_segments is a List<String>
5
Unsupported operation: removeLast
5

I don't get it, what am I missing?


Solution

  • apparently wrapping the list as follows fixes the issue

    final _segments = [...Uri.parse(_routeInfo.location).pathSegments];

    import 'package:flutter/material.dart';
    
    void main() {
      final _list = ['1', '2', '3', '4'];
      print('_list is a ${_list.runtimeType}');
    
      print('${_list.last}');
      try {
        _list.removeLast();
      } catch (e) {
        print(e);
      }
      print('${_list.last}');
      
      final _routeInfo = RouteInformation(location: '/user/info/5');
    
    -  final _segments = Uri.parse(_routeInfo.location).pathSegments;
    
    +  final _segments = [...Uri.parse(_routeInfo.location).pathSegments];
    
      print('_segments is a ${_segments.runtimeType}');
      print('${_segments.last}');
      try {
        _segments.removeLast();
      } catch (e) {
        print(e);
      }
      print('${_segments.last}');
    }