Abdelrhman Talat
Abdelrhman Talat

Reputation: 1317

Dart range operator

I have been looking at Dart and I was wondering if it has a range operator like the one Kotlin has https://kotlinlang.org/docs/reference/ranges.html or anything similar to that.

Upvotes: 14

Views: 16407

Answers (6)

zzc
zzc

Reputation: 11

for (int index in Iterable.generate(4)) {
  // Loop body
}

Upvotes: 1

DiyorbekDev
DiyorbekDev

Reputation: 774

There is no such operator in Dart at the current time.

but try these codes

1.

List<int> range(int from, int from)=>List.generate(10,(i)=>i);
Iterable<int> range(int from,int to,[int stepSize=1]) sync*{
 for(int i = from;i<to;i+=stepSize){
   yield i;
  }
}
  Iterable<int> to(int end, [int stepSize = 1]) sync* {
    if (this <= end) {
      for (var i = this; i < end; i += stepSize) yield i;
    } else {
      for (var i = this; i > end; i -= stepSize) yield i;
    }
  }
}

Upvotes: 1

Cyrax
Cyrax

Reputation: 827

You can use range_type dart package for using ranges.

import 'package:range_type/predefined_ranges.dart';

void main() {
  final july = DateTimeRange.parse('[2022-07-01, 2022-08-01)');

  final scheduleDate1 = DateTime(2022, 07, 02);
  final scheduleDate2 = DateTime(2022, 08, 07);

  final workingDays = DateTimeRange.parse('[2022-07-20, 2022-08-15)');

  print('Is scheduleDate1 in July? ${july.containsElement(scheduleDate1)}');
  print('Is scheduleDate2 in July? ${july.containsElement(scheduleDate2)}');
  print('Is workingDays overlaps? ${july.overlap(workingDays)}');
  print('workingDays intersection: ${july.intersection(workingDays)}');
  print('workingDays union: ${july.union(workingDays)}');
  print('july difference workingDays: ${july.difference(workingDays)}');
}

Upvotes: -1

Ber
Ber

Reputation: 41873

For quite some time (since September 2014), Iterable.generate(n) has been available which iterate integers from 0 to n-1. Currently that seems to be the closed you can get to a range() like function.

See the discussion in this issue 7775

Usage example:

Iterable.generate(5).forEach((i) => print(i));

Upvotes: 4

Pablo Barrera
Pablo Barrera

Reputation: 10963

You could use List.generate, like this:

var list = List.generate(4, (i) => i);
print(list); // prints [0, 1, 2, 3]

Or

List _range(int from, int to) => List.generate(to - from + 1, (i) => i + from);
print(_range(3, 6)); // prints [3, 4, 5, 6]

Upvotes: 20

lrn
lrn

Reputation: 71828

There is no such operator in Dart at the current time.

Upvotes: 4

Related Questions