Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 在flatter中如何在没有项目生成器的情况下使用索引_Flutter_Dart_Flutter Layout - Fatal编程技术网

Flutter 在flatter中如何在没有项目生成器的情况下使用索引

Flutter 在flatter中如何在没有项目生成器的情况下使用索引,flutter,dart,flutter-layout,Flutter,Dart,Flutter Layout,我试图在页面上显示firestore中的卡片列表。此列表是从另一页调用的。如果我手动设置一个整数值,产品将根据该值显示卡片,但是如果我没有设置一个int值,我将得到一个错误。如何在不使用itembuilder的情况下获取卡片的索引。这是代码 child: Center( child: InkWell( onTap: () async {

我试图在页面上显示firestore中的卡片列表。此列表是从另一页调用的。如果我手动设置一个整数值,产品将根据该值显示卡片,但是如果我没有设置一个int值,我将得到一个错误。如何在不使用itembuilder的情况下获取卡片的索引。这是代码

child: Center(
                                    child: InkWell(
                                  onTap: () async {
                                    await productProvider
                                        .loadProductsByCategory(
                                            categoryName: categoryProvider
                                                .categories[0].category);
                                    changeScreen(
                                        context,
                                        CategoryScreen(
                                          categoryModel:
                                              categoryProvider.categories[0],
                                        ));
                                  },
                                  child: Text(widget.product.category),
                                )),
这就是我遇到的问题。只需使用[0]或任何整数即可。但是我想调用索引,这样一旦我点击分类,它就会加载特定的一个及其所有的产品。我已附上完整的代码

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

class NewProductScreen extends StatefulWidget {
  final ProductModel product;

  const NewProductScreen({Key key, this.product}) : super(key: key);

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

class _NewProductScreenState extends State<NewProductScreen> {
  @override
  Widget build(BuildContext context) {
    final productProvider = Provider.of<ProductProvider>(context);
    final categoryProvider = Provider.of<CategoryProvider>(context);

    return Scaffold(
        body: CustomScrollView(slivers: <Widget>[
          SliverToBoxAdapter(
            child: Column(
              children: <Widget>[
                Container(
                  margin:
                  EdgeInsets.only(top: 5, bottom: 5, right: 2),
                  width: MediaQuery
                      .of(context)
                      .size
                      .width / 3,
                  height: MediaQuery
                      .of(context)
                      .size
                      .height / 30,
                  child: Center(
                      child: InkWell(
                        onTap: () async {
                          await productProvider.loadProductsByCategory(
                              categoryName: categoryProvider
                                  .categories[0].category);
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      CategoryScreen(
                                        categoryModel: categoryProvider
                                            .categories[0],
                                      )));
                        },
                        child: Text(widget.product.category),
                      )),
                ),
              ],
            ),
          )
        ]));
  }
}

class CategoryScreen extends StatefulWidget {
  final CategoryModel categoryModel;

  const CategoryScreen({Key key, this.categoryModel}) : super(key: key);

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

class _CategoryScreenState extends State<CategoryScreen> {
  @override
  Widget build(BuildContext context) {
    final productProvider = Provider.of<ProductProvider>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Category Filter"),
      ),
      body: SafeArea(
          child: ListView(
            children: <Widget>[
              Container(
                height: MediaQuery
                    .of(context)
                    .size
                    .height / 10,
                decoration: BoxDecoration(
                    color: Colors.orange.withOpacity(0.5),
                    image: DecorationImage(
                        image: NetworkImage(widget.categoryModel.icon))),
                child: Center(
                  child: Text(
                    widget.categoryModel.category,
                    style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 50,
                    ),
                  ),
                ),
              ),
              Column(
                children: productProvider.productsByCategory
                    .map((e) =>
                    GestureDetector(
                      onTap: () {
                        Navigator
                            .push(context, MaterialPageRoute(builder: (context)
                        =>
                            NewProductScreen(
                              product: e,
                            )
                        );
                            
                      },
                      child: CategoryProductCard(
                        product: e,
                      ),
                    ))
                    .toList(),
              )
            ],
          )),
    );
  }
}

//Category ProductCard

class CategoryProductCard extends StatefulWidget {
  final ProductModel product;

  const CategoryProductCard({Key key, this.product}) : super(key: key);

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

class _CategoryProductCardState extends State<CategoryProductCard> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 4, right: 4, top: 4, bottom: 10),
      child: Container(
        height: 110,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                  color: Colors.grey[300],
                  offset: Offset(-2, -1),
                  blurRadius: 5),
            ]),
//            height: 160,
        child: Row(
          children: <Widget>[
            Container(
              width: 140,
              height: 120,
              child: ClipRRect(
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20),
                  topLeft: Radius.circular(20),
                ),
                child: Image.network(
                  widget.product.images[0],
                  fit: BoxFit.fill,
                ),
              ),
            ),
            Expanded(
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Text(widget.product.title)),
                      Padding(
                        padding: EdgeInsets.all(8),
                        child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                    color: Colors.grey[300],
                                    offset: Offset(1, 1),
                                    blurRadius: 4),
                              ]),
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 25,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(right: 8.0),
                        child: Text(
                          "\N${widget.product.price}",
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

//Category Model

class CategoryModel {
  static const ID = "id";
  static const CATEGORY = "category";
  static const ICON = "icon";

  int _id;
  String _category;
  String _icon;
  bool isSelected;

  int get id => _id;

  String get category => _category;

  String get icon => _icon;

  CategoryModel.fromSnapshot(DocumentSnapshot snapshot) {
    _id = snapshot.data[ID];
    _category = snapshot.data[CATEGORY];
    _icon = snapshot.data[ICON];
  }
}

// Category Provider

class CategoryProvider with ChangeNotifier {
  CategoryServices _categoryServices = CategoryServices();
  List<CategoryModel> categories = [];

  CategoryModel categoryModel;

  CategoryProvider.initialize() {
    loadCategories();
  }

  loadCategories() async {
    categories = await _categoryServices.getCategories();
    notifyListeners();
  }

  loadSingleCategory({String singleCat}) async {
    categoryModel =
    await _categoryServices.getCategoryByName(category: singleCat);
    notifyListeners();
  }
}

// Category Service

class CategoryServices {
  String collection = "categories";
  Firestore _firestore = Firestore.instance;

  Future<List<CategoryModel>> getCategories() async =>
      _firestore.collection(collection).getDocuments().then((result) {
        List<CategoryModel> categories = [];
        for (DocumentSnapshot category in result.documents) {
          categories.add(CategoryModel.fromSnapshot(category));
        }
        return categories;
      });

  Future<CategoryModel> getCategoryByName({String category}) =>
      _firestore
          .collection(collection)
          .document(category.toString())
          .get()
          .then((doc) {
        return CategoryModel.fromSnapshot(doc);
      });
}

// Product Model


class ProductModel {
  static const ID = "id";
  static const TITLE = "Product Title";
  static const Images = "Product Images";
  static const PRICE = "Product Price";
  static const CATEGORY = "Product Category";

  // static const QUANTITY = "Product Quantity";
  static const BRAND = "Product Brand";


  String _id;
  String _title;
  List _images;

  String _category;
  String _brand;


// int _quantity;
  double _price;


  String get id => _id;

  String get title => _title;

  List get images => _images;

  String get brand => _brand;

  String get category => _category;


// int get quantity => _quantity;

  double get price => _price.floorToDouble();
  

  ProductModel.fromSnapshot(DocumentSnapshot snapshot) {
    _id = snapshot.data[ID];
    _brand = snapshot.data[BRAND];
    _price = snapshot.data[PRICE];
    _category = snapshot.data[CATEGORY];
    _title = snapshot.data[TITLE];
    _images = snapshot.data[Images];

  }
}

class ProductProvider with ChangeNotifier {
  ProductServices _productServices = ProductServices();
  List<ProductModel> products = [];
  List<ProductModel> productsByVendor = [];
  List<ProductModel> productsByCategory = [];

  ProductProvider.initialize() {
    loadProducts();
  }

  loadProducts() async {
    products = await _productServices.getProducts();
    notifyListeners();
  }

  Future loadProductsByCategory({String categoryName}) async {
    productsByCategory =
    await _productServices.getProductsByCategory(category: categoryName);
    notifyListeners();
  }
}

class ProductServices {
  String collection = "appProducts";
  Firestore _firestore = Firestore.instance;

  Future<List<ProductModel>> getProducts() async =>
      _firestore.collection(collection).getDocuments().then((result) {
        List<ProductModel> products = [];
        for (DocumentSnapshot product in result.documents) {
          products.add(ProductModel.fromSnapshot(product));
        }
        return products;
      });

  Future<List<ProductModel>> getProductsByCategory({String category}) async =>
      _firestore
          .collection(collection)
          .where("Product Category", isEqualTo: category)
          .getDocuments()
          .then((result) {
        List<ProductModel> products = [];
        for (DocumentSnapshot product in result.documents) {
          products.add(ProductModel.fromSnapshot(product));
        }
        return products;
      });
}

import'包:cloud_firestore/cloud_firestore.dart';
进口“包装:颤振/材料.省道”;
导入“包:provider/provider.dart”;
类NewProductScreen扩展StatefulWidget{
最终产品模型产品;
constNewProductScreen({Key-Key,this.product}):super(Key:Key);
@凌驾
_NewProductScreenState createState()=>\u NewProductScreenState();
}
类_NewProductScreenState扩展状态{
@凌驾
小部件构建(构建上下文){
final productProvider=Provider.of(上下文);
final categoryProvider=Provider.of(上下文);
返回脚手架(
主体:自定义滚动视图(条子:[
滑动双轴适配器(
子:列(
儿童:[
容器(
保证金:
仅限边集(顶部:5,底部:5,右侧:2),
宽度:MediaQuery
.of(上下文)
.尺寸
.宽度/3,
高度:MediaQuery
.of(上下文)
.尺寸
.身高/30,
儿童:中心(
孩子:InkWell(
onTap:()异步{
等待productProvider.loadProductsByCategory(
categoryName:categoryProvider
.categories[0]。类别);
导航器。推(
上下文
材料路线(
生成器:(上下文)=>
分类屏幕(
categoryModel:categoryProvider
.类别[0],
)));
},
子项:文本(widget.product.category),
)),
),
],
),
)
]));
}
}
类CategoryScreen扩展StatefulWidget{
最终分类模型分类模型;
const CategoryScreen({Key-Key,this.categoryModel}):super(Key:Key);
@凌驾
_CategoryScreenState createState()=>U CategoryScreenState();
}
类_CategoryScreenState扩展状态{
@凌驾
小部件构建(构建上下文){
final productProvider=Provider.of(上下文);
返回脚手架(
appBar:appBar(
标题:文本(“类别过滤器”),
),
正文:安全区(
子:ListView(
儿童:[
容器(
高度:MediaQuery
.of(上下文)
.尺寸
.身高/10,
装饰:盒子装饰(
颜色:颜色。橙色。不透明度(0.5),
图像:装饰图像(
image:NetworkImage(widget.categoryModel.icon)),
儿童:中心(
子:文本(
widget.categoryModel.category,
样式:TextStyle(
fontWeight:fontWeight.w700,
尺寸:50,
),
),
),
),
纵队(
子项:productProvider.productsByCategory
.map((e)=>
手势检测器(
onTap:(){
领航员
.push(上下文,MaterialPage路由)(生成器:(上下文)
=>
新产品屏幕(
产品:e,,
)
);
},
子:类别产品卡(
产品:e,,
),
))
.toList(),
)
],
)),
);
}
}
//类别产品卡
类CategoryProductCard扩展StatefulWidget{
最终产品模型产品;
const CategoryProductCard({Key-Key,this.product}):super(Key:Key);
@凌驾
_CategoryProductCardState createState()=>\u CategoryProductCardState();
}
类_CategoryProductCardState扩展状态{
@凌驾
小部件构建(构建上下文){
返回填充(
填充:仅限常量边集(左:4,右:4,顶部:4,底部:10),
子:容器(
身高:110,
装饰:盒子装饰(
颜色:颜色,白色,
边界半径:边界半径。圆形(20),
boxShadow:[
箱形阴影(
颜色:颜色。灰色[300],
偏移量:偏移量(-2,-1),
半径:5),
]),
//身高:160,
孩子:排(
儿童:[
容器(
宽度:140,
身高:120,
孩子:ClipRRect(
borderRadius:仅限borderRadius(
左下角:半径。圆形(20),
左上:半径。圆形(20),
),
孩子:Image.network(
widget.product.images[0],
fit:BoxFit.fill,
),
),
),
扩大(
子:列(
final List uniqueList = Set.from(myList).toList();


uniqueList.map((val) {
    String idx = uniqueList.indexOf(val);

    return something;
}
 @override
  Widget build(BuildContext context) {
    var  uniqueList = Set.from(['A','B','C','D','E']).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
                children: uniqueList
                    .map((e) =>
                    GestureDetector(
                      onTap: () {
                        print("--index--${uniqueList.indexOf(e)}");
//                         Navigator
//                             .push(context, MaterialPageRoute(builder: (context)
//                         =>
//                             NewProductScreen(
//                               product: e,
//                             )
//                         );
                            
                      },
                      child: Text('value :$e - index:${uniqueList.indexOf(e)}'),
                      
                    ))
                    .toList(),
              )
      ),
    
    );
  }