首页 > 解决方案 > 创建一个条件,可以在颤动中以正确的方式将数据集索引在一起

问题描述

我有一个关于何时使用两个不同数据集(图像和用户)的问题。图像数据集包括产品的图像,用户数据集包括产品信息。这两个数据集都包含很好的 ID,因为这是我可以识别哪些图片与正确的产品信息相关联的方式。

所以我现在遇到的问题是以某种方式创造一个条件,可以以正确的方式将数据集索引在一起。

`

return Column(
   crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
  Categories(),

  Expanded(
      child:ListView.builder(
  itemCount: users.length,
  itemBuilder: (context, index) {
   return Container(
     padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
     height: 220,
     width: double.maxFinite,
     child: Card(
     shape: RoundedRectangleBorder(
         borderRadius: BorderRadius.circular(15.0)),
       elevation: 3,

     child: InkWell(
    onTap: () {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => DetailsScreen(
           links: images[index],
            products: users[index],
          ),
        ),
      );
    // Function is executed on tap.
          },

              child: new Stack(
           children: <Widget>[
            Container(
              margin: new EdgeInsets.symmetric(
                 vertical: 16.0
               ),

             alignment: FractionalOffset.centerLeft,
         child: new Image.network(images[index].plink.toString() ?? ''
         ),
      ),
       Container(
         margin: new EdgeInsets.fromLTRB(96.0, 16.0, 16.0, 16.0),
         constraints: new BoxConstraints.expand(),
         child: new Column(
           crossAxisAlignment: CrossAxisAlignment.start,
           children: <Widget>[
             new Container(height: 2.0),
             new Text("${users[index].productNameBold??'NoInformation'}",
               style: Style.headerTextStyle,
             ),
             new Container(height: 5.0),
             new Text("${users[index].category??'NoInformation'}",
                 style: Style.baseTextStyle
             ),

             new Container(
                 margin: new EdgeInsets.symmetric(vertical: 2.0),
                 height: 2.0,
                 width: 24.0,
                 color: Colors.black
             ),

             new Container(height: 5.0),
             new Text("${users[index].country??'NoInformation'}",
                 style: Style.baseTextStyle
             ),
             new Container(height: 25.0),
             new Row(
               children: <Widget>[
                 new Text("${users[index].price??'NoInformation'} SEK",
                   style: Style.pricetextdiscount,
                 ),
                 new Container(width: 8.0),
                 new Text("129",
                   style: Style.pricetextprevious,
                 ),
               ],
             ),
           ],
         ),
       ),
        ]),
         ),
      ),
        );
     },
      ),
    ),
     ],
      );`

编辑...............................................

你好!所以现在我制作了一个新的 dart 文件,我在其中插入了下面的代码,我得到了帮助。但是我现在不明白的是激活代码是它将在我的flutter应用程序中运行。因为在调试器中结果显示,即使我运行应用程序,combine 的索引也是 0。所以我想我没有以正确的方式调用文件?

import 'package:shop_app/models/Image.dart';
import 'package:shop_app/models/ProductInfo.dart';



void main() {


var pictureList  = new List<Images>();
var userList  = new List<ProductInfo>();


List<Combine> combineList = new List<Combine>();
userList.forEach((user) {
  Images picture = pictureList.firstWhere((pic) => pic.productId == user.productId);
  if (picture != null) {
    combineList.add(Combine(user, picture));
  }
});

combineList.forEach((combine) {
  print("User id: ${combine.user.productId}  User name: 
${combine.user.productNameBold}");
  print(
      "Picture id: ${combine.product.productId}  Picture url: 
 ${combine.product.plink}");
  print("---------------------------------- \n");
   });
 }



 class Combine {
 ProductInfo user;
 Images product;
 Combine(this.user, this.product);
  }

标签: flutterdataset

解决方案


我认为您需要创建一个包含您的用户和产品的新类。然后你应该运行一个循环并匹配用户和产品的 id。这是一个例子

void main() {
  List<User> userList = [
    User(1, "one"),
    User(2, "two"),
    User(3, "three"),
  ];
  List<Product> pictureList = [
    Product(1, "oneImg"),
    Product(2, "twoImg"),
    Product(3, "threeImg"),
  ];
  List<Combine> combineList = new List<Combine>();
  userList.forEach((user) {
    Product picture = pictureList.firstWhere((pic) => pic.id == user.id);
    if (picture != null) {
      combineList.add(Combine(user, picture));
    }
  });

  combineList.forEach((combine) {
    print("User id: ${combine.user.id}  User name: ${combine.user.name}");
    print(
        "Picture id: ${combine.product.id}  Picture url: ${combine.product.image}");
    print("---------------------------------- \n");
  });
}

class User {
  int id;
  String name;
  User(this.id, this.name);
}

class Product {
  int id;
  String image;
  Product(this.id, this.image);
}

class Combine {
  User user;
  Product product;
  Combine(this.user, this.product);
}

输出:

User id: 1  User name: one
Product id: 1  Product image: oneImg
---------------------------------- 

User id: 2  User name: two
Product id: 2  Product image: twoImg
---------------------------------- 

User id: 3  User name: three
Product id: 3  Product image: threeImg
---------------------------------- 

在您的情况下,将用户和产品组合在一个列表中,然后在您的小部件中使用该列表。

完整代码:

import 'dart:convert';

import 'package:flutter/material.dart';

import 'APIE.dart';
import 'Image.dart';
import 'ProductInfo.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      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> {
  var pictureList = new List<Images>();
  var userList = new List<ProductInfo>();
  bool dataGet = false;



  _getImage() {
    API.getImage().then((response) {
        Iterable list = json.decode(response.body);
        pictureList = list.map((model) => Images.fromJson(model)).toList();
        _conmineList();
    });
  }

  _getUsers() {
    API.getUsers().then((response) {
        Iterable list = json.decode(response.body);
        userList = list.map((model) => ProductInfo.fromJson(model)).toList();
        _getImage();
    });
  }

  _conmineList(){
    userList.forEach((user) {
      Images picture = pictureList.firstWhere((pic) => pic.productId == user.productId);
      if (picture != null) {
        combineList.add(Combine(user, picture));
      }
    });
    setState(() {
      dataGet = true;
    });
  }




  List<Combine> combineList = new List<Combine>();

  @override
  void initState() {
    _getUsers();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: SingleChildScrollView(
          child: dataGet?ListView.builder(
            itemCount: userList.length,
            shrinkWrap: true,
            itemBuilder: (context, index) => ListTile(
              title: Text("${userList[index].productId}"),
              subtitle: Text("${pictureList[index].productId}" + "${combineList[index].product.productId}" ),

            ),
          ):Center(child: CircularProgressIndicator()),
        ));
  }
}


class Combine {
  ProductInfo user;
  Images product;
  Combine(this.user, this.product);
}

推荐阅读