Rahul Lohra
Rahul Lohra

Reputation: 854

How to extend a class when one of the optional argument is not a member variable and it is required?

Here is the code. We have a TabController (from sdk), I am extending this TabController class:

class TabController extends ChangeNotifier {
   int length;
   TabController({ int initialIndex = 0,
      @required this.length, 
      @required TickerProvider vSync
   }):assert(length != null),
       assert(vSync != null);

} //end of TabController

class AppTabController extends TabController {

    AppTabController(int mInitialIndex,
       int mLength,
      TickerProvider mVsync):super(length: mLength, mVsync: vsync ){}

}

Now this AppTabController's constructor is giving syntax error. Seems like I can't extend TabController class because:

  1. vsync is not a member variable of TabController
  2. There are some assertions in TabController constructor itself due to which if the required args are not passed then it will crash.

These are the compile errors:

  1. error: The named parameter vsync isn't defined

Upvotes: 4

Views: 2091

Answers (2)

Chinnon Santos
Chinnon Santos

Reputation: 455

@RahulLohra

If you use your own TickerProvider (as in the @yahocho example), you will need to implement the correct abstract method createTicker, as follows:

import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';

class MyTickerProvider extends TickerProvider{
  @override
  Ticker createTicker(onTick) =>
      Ticker(onTick, debugLabel: kDebugMode ? 'created by $this' : null);
}

Notes:

  • Name class using UpperCamelCase. (Please, see Effective Dart guidelines)
  • If you return null in createTicker, you will see an error in the log every time you run the animation.

Upvotes: 0

yaho cho
yaho cho

Reputation: 1779

  1. this.length requires member variable.
  2. @required requires assert
  3. use : instead of =
  4. make a class extended TickerProvider because it is abstract class. I made myTickerProvider as the example.
AppTabController appTabController = new AppTabController(mLength:10, mVsync:new myTickerProvider());

class TabController extends ChangeNotifier {
  int length;
  TabController({
    int initialIndex = 0,
    @required this.length,
    @required TickerProvider vSync
  }) : assert(length != null),
       assert(vSync != null);
} //end of TabController

class AppTabController extends TabController {

  AppTabController({int mInitialIndex,
      int mLength,
      TickerProvider mVsync}):super(length: mLength, vSync: mVsync);
}


class myTickerProvider extends TickerProvider{
  @override
  Ticker createTicker(onTick) {
    // TODO: implement createTicker
    return null;
  }
}

Upvotes: 2

Related Questions