简体   繁体   English

错误:在此小部件 Flutter [PropertiesGrid] 上方找不到正确的提供程序

[英]Error: Could not find the correct Provider above this widget Flutter [PropertiesGrid]

I am trying to call a simple GridWiget inside my home page我试图在我的主页中调用一个简单的GridWiget

and this is MyHomePage StatefulWidget :这是MyHomePage StatefulWidget

import './app_theme.dart';
import 'package:flutter/material.dart';
import './widgets/properties_grid.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  var _showOnlyFavorites = false;
  AnimationController animationController;
  bool multiple = true;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    super.initState();
  }

  Future<bool> getData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 0));
    return true;
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return PropertiesGrid(_showOnlyFavorites);
                        }
                      },
                    ),
                  ),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    multiple ? Icons.dashboard : Icons.view_agenda,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

and this is PropertiesGrid StatelessWidget :这是PropertiesGrid StatelessWidget

import 'package:aradi_online_vtwo/providers/properties.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../providers/properties.dart';
import './property_item.dart';

class PropertiesGrid extends StatelessWidget {
  final bool showFavs;

  PropertiesGrid(this.showFavs);

  @override
  Widget build(BuildContext context) {
    final productsData = Provider.of<Properties>(context);
    final products = showFavs ? productsData.favoriteItems : productsData.items;
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),
      itemCount: products.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
            value: products[i],
            child: PropertyItem(
                ),
          ),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ),
    );
  }
}

and the dummy provider data is something looks like this below one:虚拟provider数据如下所示:

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

class Properties with ChangeNotifier {
  List<Property> _items = [
    Property(
      id: 'p1',
      purpose: '',
      title: 'House Title sdfsdffdgdfgdfs',
    ),
    Property(
      id: 'p3',
      purpose: '',
      title: 'land title',
    ),
  ];

  List<Property> get items {
    return [..._items];
  }

  List<Property> get favoriteItems {
    return _items.where((propItem) => propItem.isFavorite).toList();
  }

  Property findById(String id) {
    return _items.firstWhere((prop) => prop.id == id);
  }

  void addProperty(Property property) {
    final newProperty = Property(
      id: DateTime.now().toString(),
      purpose: property.purpose,
      title: property.title,
    );
    _items.add(newProperty);
    notifyListeners();
  }

  void updateProperty(String id, Property newProperty) {
    final propIndex = _items.lastIndexWhere((prop) => prop.id == id);
    if (propIndex >= 0) {
      _items[propIndex] = newProperty;
      notifyListeners();
    } else {
      print('...');
    }
  }

  void deleteProperty(String id) {
    _items.removeWhere((prop) => prop.id == id);
    notifyListeners();
  }
}

and the GridItem is the below code: GridItem是下面的代码:

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

import '../providers/property.dart';

class PropertyItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final property = Provider.of<Property>(context, listen: false);
    // final cart = Provider.of<Cart>(context, listen: false);
    return InkWell(
      onTap: () => {},
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
        ),
        elevation: 7,
        margin: EdgeInsets.all(2),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15),
                topRight: Radius.circular(15),
              ),
              // color: Colors.transparent,
              child: Image.asset(
                property.image,
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: Consumer<Property>(
                builder: (ctx, property, _) => IconButton(
                  icon: Icon(
                    property.isFavorite ? Icons.favorite : Icons.favorite_border,
                  ),
                  color: Colors.red,
                  onPressed: () {
                    property.toggleFavoriteStatus();
                  },
                ),
              ),
            ),
            Positioned(
                  right: 20,
                  top: 100,
                  child: Container(
                    width: 300,
                    color: Colors.black54,
                    padding: EdgeInsets.symmetric(
                      vertical: 5,
                      horizontal: 20,
                    ),
                    child: Text(
                      property.title,
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                      ),
                      softWrap: true,
                      overflow: TextOverflow.fade,
                    ),
                  ),
                )
          ],
        ),
      ),
    );
  }
}

and this is the ModelProvider :这是ModelProvider

import 'package:flutter/foundation.dart';

class Property with ChangeNotifier {
  final String id;
  final String purpose;
  final String title;
  bool isFavorite;

  Property({
    @required this.id,
    @required this.purpose,
    @required this.title,
  });

  void toggleFavoriteStatus() {
    isFavorite = !isFavorite;
    notifyListeners();
  }
}

As the error in this part:作为这部分的错误:

return PropertiesGrid(_showOnlyFavorites);

I hope some one could help I post all Information could be...我希望有人可以帮助我发布所有信息可能是......

You have to add a change notifier provider as a parent in order to access the property model from descendent widgets.您必须添加一个更改通知提供程序作为父级,以便从后代小部件访问属性 model。

ChangeNotifierProvider(
  create: (context) => Property(),
  child: PropertiesGrid(_showOnlyFavorites),
),

Now you can access the property change notifier model using Provider.of<Property>(context, listen: false);现在您可以使用Provider.of<Property>(context, listen: false); or using Consumer .或使用Consumer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 颤振提供者错误:在此小部件上方找不到正确的提供者 - flutter provider error : Could not find the correct provider above this widget Flutter 中的提供程序出现错误“无法在此 X Widget 上方找到正确的提供程序” - Provider in Flutter with error "Could not find the correct provider above this X Widget" Flutter 错误:找不到正确的提供程序<user>在此 Wrapper Widget 上方</user> - Flutter Error: Could not find the correct Provider<User> above this Wrapper Widget Flutter 错误:找不到正确的提供程序<cart>在此 ProductLandingPage 小部件上方</cart> - Flutter Error : Could not find the correct Provider<Cart> above this ProductLandingPage Widget 在此小部件上方找不到正确的提供程序 - Flutter - Could not find the correct Provider above this Widget - Flutter Flutter 错误:找不到正确的提供程序<MyUser>在这个 SettingsForm 小部件上方 - Flutter Error: Could not find the correct Provider<MyUser> above this SettingsForm Widget Flutter 错误:找不到正确的提供者<myuser>在这个包装器小部件上方</myuser> - Flutter Error: Could not find the correct Provider<MyUser> above this wrapper widget 错误:找不到正确的提供者<clientsprovider>在 flutter 中的此客户小部件上方?</clientsprovider> - Error: Could not find the correct Provider<ClientsProvider> above this Clients Widget in flutter? 错误无法在此小部件上方找到正确的提供程序 - Error could not find the correct provider above this widget 错误:在此小部件上方找不到正确的提供者 - Error: Could not find the correct Provider above this widget
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM