【问题标题】:Acessing List items on another class访问另一个类的列表项
【发布时间】:2020-05-13 13:31:32
【问题描述】:

您好,我想知道如何访问创建列表的不同类上的列表项。特别是我想访问 Restaurant Screen 类上的 restaurantList 项。

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/models/restaurant.dart';


List<Restaurant> restaurantList=[
  Restaurant(image:"kfcloja.jpg",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
  Restaurant(image:"dominos.jpg",distance: "0.9 miles away",location:"Downtown",restaurantName: "Dominos"),
  Restaurant(image:"kfclogo.png",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),

];//I would like to access the items on the list
class RestaurantWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 350,
      child: ListView.builder(
          scrollDirection: Axis.vertical,
          itemCount: restaurantList.length,
          itemBuilder: (_, index) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(

                decoration: BoxDecoration(
                    border: Border.all(
                        width: 1.0,
                        color: Colors.grey[100]

                    ),
                    borderRadius: BorderRadius.circular(20)
                ),
                child: Row(
                  children: <Widget>[
                    Container(
                        width: 150,
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: Image.asset("images/${restaurantList[index].image}",fit:BoxFit.cover ,)
                        )
                    ),

                    Padding(
                      padding: const EdgeInsets.all(3.0),
                      child: Container(
                        padding: EdgeInsets.all(2),
                        height: 70,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text("${restaurantList[index].restaurantName}",style: TextStyle(fontWeight: FontWeight.bold),),
                            Row(
                              children: <Widget>[
                                Icon(Icons.star,size: 15,color:Colors.yellowAccent,),
                                Icon(Icons.star,size: 15,color:Colors.yellowAccent),
                                Icon(Icons.star,size: 15,color:Colors.yellowAccent),
                                Icon(Icons.star,size: 15,color:Colors.yellowAccent),
                                Icon(Icons.star_half,size: 15,color:Colors.yellowAccent),

                              ],
                            ),
                            Text("${restaurantList[index].location}"),
                            Text("${restaurantList[index].distance}"),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
    );


  }
}

在这个班级

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/widgets/menu_widget.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';

class RestaurantScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: 400,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                Image.asset(
                  "images/kfcloja.jpg",
                  fit: BoxFit.cover,
                ),
                Positioned(
                  child: IconButton(
                    icon: Icon(Icons.keyboard_arrow_left,size: 40,color: Colors.white,),
                    onPressed: (){},
                  ),
                  top: 15,

                )
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 14, left: 14, right: 14),
              child: Container(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        "Restaurant KFC",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                      ),
                      Text(
                        "0.2 miles away",
                        style: TextStyle(
                          fontSize: 16,
                        ),
                      ),
                    ],
                  ),
                  Align(
                    alignment: Alignment.topLeft,
                    child: SmoothStarRating(
                        allowHalfRating: false,
                        starCount: 5,
                        size: 20.0,
                        filledIconData: Icons.blur_off,
                        halfFilledIconData: Icons.blur_on,
                        color: Colors.yellowAccent,
                        borderColor: Colors.yellowAccent,
                        spacing: 0.0),
                  ),
                  Align(
                    alignment: Alignment.topLeft,
                    child: Text("200 Main St, New york"),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                        left: 30, right: 30, top: 20, bottom: 5),
                    child: Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          FlatButton.icon(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                            ),
                            color: Theme.of(context).primaryColor,
                            icon: Icon(
                              Icons.rate_review,
                              color: Colors.white,
                            ),
                            label: Text(
                              'Reviews',
                              style: TextStyle(color: Colors.white),
                            ),
                            onPressed: () {},
                          ),
                          FlatButton.icon(
                            shape: new RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(10.0),
                            ),
                            color: Theme.of(context).primaryColor,
                            icon: Icon(
                              Icons.contact_phone,
                              color: Colors.white,
                            ),
                            label: Text(
                              'Contact',
                              style: TextStyle(color: Colors.white),
                            ),
                            onPressed: () {},
                          )
                        ],
                      ),
                    ),
                  ),
                     Text(
                      "Menu",
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 20),
                    ),
                     MenuWidget(),


                ],
              )
              ),
            )
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 你知道如何从RestaurantWidget打开RestaurantScreen吗?
  • 所以不可能吧???
  • 如果我在餐厅屏幕上列出我可以从 RestaurantWidget 访问它???
  • @ValdoAmaral 请检查以下解决方案,如果有问题请告诉我
  • 是可能的。检查 Ravindra 的答案。

标签: flutter dart


【解决方案1】:

您可以按如下方式从一个屏幕向另一个屏幕发送和接收数据,您需要使用Navigator,在下面的示例中,我将数据从类A发送到类B如下

Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) => B(bean: restaurantList[index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
);

B 类中,您需要创建 contrsutor 以接收来自 A 的数据,如下所示

class B extends StatefulWidget {
  Restaurant bean;

  B ({Key key, @required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean" 

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _B();
  }
}

请检查它的示例以将数据从一个类传递到另一个类

A类将数据发送到B

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import 'B.dart';
import 'Fields.dart';

    class A extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
        return _A();
      }
    }

    class _A extends State<A> {

      Widget build(BuildContext context) {
        return MaterialApp(
            title: 'Screen A',
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              primaryColor: Colors.red,
              accentColor: Color(0xFFFEF9EB),
            ),
            home: Scaffold(
                appBar: new AppBar(),
                body: Container(
                  margin: EdgeInsets.all(20.0),
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: Text("Screen A"),
                      ),
                      Expanded(
                        child: ListView.builder(
                            itemCount: fields.length,
                            itemBuilder: (BuildContext ctxt, int index) {
                              return ListTile(
                                title: new Text("Rating #${fields[index].rating}"),
                                subtitle: new Text(fields[index].title),
                                onTap: (){

                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => B(bean: fields [index])), //// HERE B IS THE CLASS ON WHICH YOU NEED TO CARRY DATA FROM CLASS A
                                  );
                                },
                              );
                            }),
                      )
                    ],
                  ),
                )));
      }
    }

    List<Fields> fields = [
      new Fields(
        'One',
        1,
      ),
      new Fields(
        'Two',
        2,
      ),
      new Fields(
        'Three',
        3,
      ),
      new Fields(
        'Four',
        4,
      ),
      new Fields(
        'Five',
        5,
      ),
    ];

现在检查从A类接收数据的B

import 'package:flutter/material.dart';

import 'Fields.dart';


    class B extends StatefulWidget{

      Fields bean;

      B ({Key key, @required this.bean}) : super(key: key); ////YOU WILL GET THE DATA HERE FROM THE CONSTRUCTOR , AND USE IT INSIDE THE CLASS LIKE "widget.bean"

      @override
      State<StatefulWidget> createState() {
        // TODO: implement createState
         return _B ();

      }

    }

    class _B extends State<B> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return MaterialApp(
            title: 'Screen A',
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              primaryColor: Colors.red,
              accentColor: Color(0xFFFEF9EB),
            ),
            home: Scaffold(
                appBar: new AppBar(),
                body: Container(
                  margin: EdgeInsets.all(20.0),
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: Center(
                          child: Text("Screen B" ,style: TextStyle(fontSize: 20.0),),
                        )
                      ),
                       Text("Rating=>>>  ${widget.bean.rating}  and Title ${widget.bean.title} ")
                    ],
                  ),
                )));
      }
    }

并且我已经使用了 Pojo 类作为列表,请检查一次

Fields.dart

class Fields {
  final String title;
  final int rating;

  Fields(this.title, this.rating);
}

上述程序的输出如下。

【讨论】:

  • @ValdoAmaral 如果它对你有用,那么请标记答案并投赞成票
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多