折旧小部件的替代方案祖先WidgetOfExactType

时间:2021-03-04 01:04:18

标签: flutter dart

我正在使用继承的小部件来构建购物车。我的购物车看起来像这样:

    class CartProvider extends InheritedWidget {
      final _cart = Cart();
    
      CartProvider({Key key, Widget child}) : super(key: key, child: child);
    
      @override
      bool updateShouldNotify(InheritedWidget oldWidget) {
        return false;
      }
    
      static Cart of(BuildContext context) {
        final widget =
            context.ancestorWidgetOfExactType(CartProvider) as CartProvider;
        return widget._cart;
      }
    }

我用 flutter 推荐的 findAncestorWidgetOfExactType 替换了ancestorWidgetOfExactType:

  final widget = context.findAncestorWidgetOfExactType<CartProvider>();

我收到此错误:

<块引用>
../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_google_places-0.2.6/lib/src/flutter_google_places.dart:74:41:
Error: Method not found: 'TypeMatcher'.
      context.ancestorStateOfType(const TypeMatcher<PlacesAutocompleteState>());
                                        ^^^^^^^^^^^                      ../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_google_places-0.2.6/lib/src/flutter_google_places.dart:74:15:
Error: The method 'ancestorStateOfType' isn't defined for the class
'BuildContext'.
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../Desktop/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining
a method named 'ancestorStateOfType'.
      context.ancestorStateOfType(const TypeMatcher<PlacesAutocompleteState>());
1.7.4/lib/src/generated/IFileOpenDialog.dart:61:47:
Error: The getter 'addressOf' isn't defined for the class 'GUID'.
 - 'GUID' is from 'package:win32/src/structs.dart' ('../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/win32-1.7.4/lib/src/structs.dart').
Try correcting the name to the name of an existing getter, or defining
a getter or field named 'addressOf'.
        GUID.fromString(CLSID_FileOpenDialog).addressOf,                
                                              ^^^^^^^^^                  ../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/win32-1.7.4/lib/src/generated/IFileOpenDialog.dart:64:46:
Error: The getter 'addressOf' isn't defined for the class 'GUID'. 

      ^                                                                  ../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-0.1.3/lib/src/utf16.dart:16:7:
Error: Struct 'Utf16' is empty. Empty structs are undefined behavior.
class Utf16 extends Struct {                                          

      ^                                                                  ../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/ffi-0.1.3/lib/src/allocation.dart:47:33:
Error: Expected type 'T' to be a valid and instantiated subtype of
'NativeType'.   final int totalSize = count * sizeOf<T>();            

                                ^                                       
                                                                        
                                                                         FAILURE: Build failed with an exception.                              

                                                                        
* Where:                                                                 Script
'/Users/hsi/Desktop/flutter/packages/flutter_tools/gradle/flutter.gradle'
line: 991
                                                                        
* What went wrong:                                                       Execution failed for task ':app:compileFlutterBuildDebug'.            

> Process 'command '/Users/hsi/Desktop/flutter/bin/flutter'' finished with non-zero exit value 1
                                                                        
* Try:                                                                   Run with --stacktrace option to get the stack trace. Run with --info
or --debug option to get more log output. Run with --scan to get full
insights.
                                                                        
* Get more help at https://help.gradle.org

我尝试了每个频道,但无法找到解决方案。请协助。

1 个答案:

答案 0 :(得分:0)

我对您的代码进行了一些格式化以使样式更好,现在可以正常工作了。还创建了一个模拟 Cart 类,但您可以改用您的类。如果有帮助,区别在于,

  1. CartProvider 有一个子字段,所以它可以很容易地插入到小部件树中(这类似于提供程序包)。这使用了“dependOnInheritedWidgetOfExactType”方法,而不是已弃用的“ancestorWidgetOfExactType”。
  2. Build 方法返回一个 CartProvider,我在其中实例化 Card() 并添加 MaterialApp 作为它的子项,这确保 MaterialApp 的每个子项都可以访问购物车。
  3. 最后,在 MyHomePage 小部件中,我使用“CartProvider.of”方法获取注入的对象,并在小部件的主体中使用它。

希望这很清楚。

一个。购物车提供商

======================================

import 'package:flutter/material.dart';
import 'cart.dart';

class CartProvider extends InheritedWidget {

  CartProvider({@required this.cart, @required this.child});

  final Cart cart;
  final Widget child;

  @override
  bool updateShouldNotify(covariant InheritedWidget oldWidget) => false;

  static Cart of(BuildContext context) {
    CartProvider provider =
        context.dependOnInheritedWidgetOfExactType<CartProvider>();
    return provider.cart;
  }
}

==============

B.主文件

==============

import 'package:flutter/material.dart';
import 'cart_provider.dart';
import 'cart.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    //Injecting cart using the created CartProvider
    return CartProvider(
      cart: Cart(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    
    //Accessing the cart inside a child widget
    final cart = CartProvider.of(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Hello'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //Using cart widget
            Text(cart.myCart),
          ],
        ),
      ),
    );
  }
}

============

c.模拟购物车类

======================

class Cart {
  final myCart = 'My cart';
}