简体   繁体   中英

Dart extension - Getting "isn't a type" error

I'm trying to extend the BuildContext, more for my learning than anything else. However, I get this error:

AppBuildContext isn't a type. Try correcting the name to match an existing type

I have added this to the file that I'm using it in:

extension AppBuildContext on BuildContext {
  ThemeData get theme {
    return Theme.of(this);
  }

  FocusScopeNode get focusScope {
    return FocusScope.of(this);
  }

  NavigatorState get navigator {
    return Navigator.of(this);
  }

  T args<T>() {
    return ModalRoute.of(this).settings.arguments as T;
  }
}

I use it like this:

class LoginView extends StatelessWidget {
  @override
  Widget build(AppBuildContext context) {
    return Scaffold(
        body: Center(
            child: VpGradientContainer(
      beginColor: initialGradientColor,
      endColor: Theme.of(context).colorScheme.primary,
      child: Column(...

What am I doing wrong?

Flutter and dart versions:

Flutter 1.22.2 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 84f3d28555 (3 days ago) • 2020-10-15 16:26:19 -0700
Engine • revision b8752bbfff
Tools • Dart 2.10.2

The AppBuildContext name is only for declaring importing restrictions. for using it, you still call BuildContext .

import 'AppBuildContext.dart'; // import the file that contains the extension manully

class LoginView extends StatelessWidget {
  @override
  Widget build(BuildContext context) { // just use normal BuildContext
    return Scaffold(
        body: Center(
            child: VpGradientContainer(
      beginColor: initialGradientColor,
      endColor: context.theme.colorScheme.primary,
      child: Column(...),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM