0

我收到以下错误 NoSuchMethodError was throw building Consumer(dirty, dependencies: [InheritedProvider]): This is the app.dart file

class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return AppState();
  }
}

class AppState extends State<App> with AfterLayoutMixin {
  final _app = AppModel();
  final _product = ProductModel();
  final _wishlist = WishListModel();
  final _shippingMethod = ShippingMethodModel();
  final _paymentMethod = PaymentMethodModel();
  final _order = OrderModel();
  final _search = SearchModel();
  final _recent = RecentModel();
  final _user = UserModel();

  @override
  void afterFirstLayout(BuildContext context) {
    Services().setAppConfig(serverConfig);
    _app.loadAppConfig();
  }

  @override
  Widget build(BuildContext context) {
    print("[AppState] build");
    return ChangeNotifierProvider<AppModel>.value(
      value: _app,
      child: Consumer<AppModel>(
        builder: (context, value,child) {
          return MultiProvider(
            providers: [
              Provider<ProductModel>.value(value: _product),
              Provider<WishListModel>.value(value: _wishlist),
              Provider<ShippingMethodModel>.value(value: _shippingMethod),
              Provider<PaymentMethodModel>.value(value: _paymentMethod),
              Provider<OrderModel>.value(value: _order),
              Provider<SearchModel>.value(value: _search),
              Provider<RecentModel>.value(value: _recent),
              ChangeNotifierProvider(builder: (context)=> UserModel()),
              ChangeNotifierProvider(builder: (context)=> CartModel()),
              ChangeNotifierProvider(builder: (context)=> CategoryModel()),
            ],
            child: MaterialApp(
              debugShowCheckedModeBanner: false,
              locale: new Locale(Provider.of<AppModel>(context).locale, ""),
              navigatorObservers: [
                FirebaseAnalyticsObserver(analytics: analytics),
              ],
              localizationsDelegates: [
                S.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
                DefaultCupertinoLocalizations.delegate,
              ],
              supportedLocales: S.delegate.supportedLocales,
              localeListResolutionCallback:
              S.delegate.listResolution(fallback: const Locale("en","")),
              home: SplashScreenAnimate(),
              routes: <String, WidgetBuilder>{
                "/home": (context) => MainTabs(),
                "/login": (context) => LoginScreen(),
                "/register": (context) => RegistrationScreen(),
                '/products': (context) => ProductsPage(),
                '/wishlist': (context) => WishList(),
                '/checkout': (context) => Checkout(),
                '/orders': (context) => MyOrders(),
                '/onboardscreen': (context) => OnBoardScreen(),
                '/blogs': (context) => BlogScreen(),
                '/notify': (context) => Notifications()
              },
              theme: Provider.of<AppModel>(context).darkTheme
                  ? buildDarkTheme().copyWith(
                  primaryColor:
                  HexColor(_app.appConfig["Setting"]["MainColor"]))
                  : buildLightTheme().copyWith(
                  primaryColor:
                  HexColor(_app.appConfig["Setting"]["MainColor"])),
            ),
          );
        },
      ),
    );
  }

运行时错误是

The relevant error-causing widget was:
  Consumer<AppModel> file:///E:/MVS/Cossetpack/lib/app.dart:202:14

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      AppState.build.<anonymous closure> (package:fstore/app.dart:252:42)
#2      Consumer.build (package:provider/src/consumer.dart:180:19)
#3      StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#5      Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#6      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
#7      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
...     Normal element mounting (23 frames)
#30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#31     Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
#32     RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1174:16)
#33     RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1145:5)
#34     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1087:17)
#35     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2620:19)
#36     RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1086:13)
#37     WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:927:7)
#38     WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:908:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)

════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Consumer<AppModel>(dirty, dependencies: [InheritedProvider<AppModel>]):
The method '[]' was called on null.
Receiver: null
Tried calling: []("Setting")

The relevant error-causing widget was: 
  Consumer<AppModel> file:///E:/MVS/Cossetpack/lib/app.dart:202:14
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      AppState.build.<anonymous closure> (package:fstore/app.dart:252:42)
#2      Consumer.build (package:provider/src/consumer.dart:180:19)
#3      StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Another exception was thrown: 'dart:ui/window.dart': Failed assertion: line 285: '<optimized out>': is not true.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
'dart:ui/window.dart': Failed assertion: line 285: '<optimized out>': is not true.
The relevant error-causing widget was: 
  Consumer<AppModel> file:///E:/MVS/Cossetpack/lib/app.dart:202:14
════════════════════════════════════════════════════════════════════════════════════════════════════

这是应用模型

class AppModel with ChangeNotifier {
  MagentoApi _magentoApi = MagentoApi();
  Map<String, dynamic> appConfig;
  bool isLoading = true;
  String message;
  bool darkTheme = false;
  String locale = "en";
  String productListLayout;
  bool showDemo = false;
  String username;
  bool isInit = false;
  String currency;
  Map<String, dynamic> currencyRate = Map<String, dynamic>();

  AppModel() {
    getConfig();
  }

  Future<bool> getConfig() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      locale = prefs.getString("language") ?? kAdvanceConfig['DefaultLanguage'];
      darkTheme = prefs.getBool("darkTheme") ?? false;
      currency = prefs.getString("currency") ??
          (kAdvanceConfig['DefaultCurrency'] as Map)['currency'];
      isInit = true;
      return true;
    } catch (err) {
      return false;
    }
  }

  void changeLanguage(String country, BuildContext context) {
    locale = country;
    Provider.of<CategoryModel>(context).getCategories(lang: country);
    notifyListeners();
  }

  void updateTheme(bool theme) {
    darkTheme = theme;
    notifyListeners();
  }

  void updateShowDemo(bool value) {
    showDemo = value;
    notifyListeners();
  }

  void updateUsername(String user) {
    username = user;
    notifyListeners();
  }

  void loadStreamConfig(config) {
    appConfig = config;
    productListLayout = appConfig['Setting']['ProductListLayout'];
    isLoading = false;
    notifyListeners();
  }

  void loadAppConfig() async {
    try {
      if (kAppConfig.indexOf('http') != -1) {
        // load on cloud config and update on air
        final appJson = await http.get(Uri.encodeFull(kAppConfig),
            headers: {"Accept": "application/json"});
        appConfig = convert.jsonDecode(appJson.body);
      } else {
        // load local config
        final appJson = await rootBundle.loadString(kAppConfig);
        appConfig = convert.jsonDecode(appJson);
      }

      productListLayout = appConfig['Setting']['ProductListLayout'];
      if (serverConfig["type"] == "magento") {
        _magentoApi.getAllAttributes();
      }
      if (serverConfig["type"] == "woo" && kAdvanceConfig['isCaching']) {
        final configCache = await Services().getHomeCache();
        if (configCache != null) {
          appConfig = configCache;
        }
      }
      isLoading = false;
      notifyListeners();
    } catch (err) {
      isLoading = false;
      message = err.toString();
      notifyListeners();
    }
  }

  void updateProductListLayout(layout) {
    productListLayout = layout;
    notifyListeners();
  }
}

class App {
  Map<String, dynamic> appConfig;

  App(this.appConfig);
}

在添加消费者小部件之前它工作正常,但现在我必须添加应用程序结帐功能,我已经添加了代码,但我收到错误请建议我在哪里做错了

4

0 回答 0