Есть ли способ изменить экран из элемента ListView? - PullRequest
1 голос
/ 19 апреля 2020

Мне нужно создать приложение для флаттера, в котором моя страница HomeScreen заполнена ListView (этот виджет заполнен данными из базы данных Firebase), и я сделал это, но теперь мне нужно сделать событие onPressed. Я сделал это с InkWell, но теперь я не знаю, как заставить каждый элемент выполнять свою функцию.

Это мой код:

// Главный экран

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
List<Function> itemFunctions = [
  () {
  print("1");
  Navigator.pop(context, MaterialPageRoute(builder: (context) => Antique()));},
      () {Navigator.pop(context, MaterialPageRoute(builder: (context) => Mediterana()));},
  () {Navigator.pop(context, MaterialPageRoute(builder: (context) => SuperKebab()));},

];
return new Scaffold(
  backgroundColor: Colors.white,
  appBar: new AppBar(
    title: new Text("e-Radauti Restaurante"),
  ),
  body: Container(
      child: StreamBuilder(
          stream: _firebaseRef.onValue,
          builder: (context, snap) {
            if (snap.hasData &&
                !snap.hasError &&
                snap.data.snapshot.value != null) {
              Map data = snap.data.snapshot.value;
              List item = [];
              data.forEach(
                  (index, data) => item.add({"key": index, ...data}));
              return ListView.builder(
                itemCount: item.length,
                itemBuilder: (context, index) {
                  return Card(
                    child: Container(
                      child: InkWell(
                        child: MediaQuery.removePadding(context: context,removeTop: true,removeBottom: true, child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                            width: 100,
                              child: CachedNetworkImage(
                                placeholder: (context, url) =>
                                    CircularProgressIndicator(),
                                imageUrl:
                                item[index]["photoUrl"].toString(),
                                errorWidget: (context, url, error) =>
                                    Icon(Icons.error),
                              ),
                          ),
                            Column(
                              children: <Widget>[
                                Text(item[index]["name"]),
                                Text(item[index]["description"]),
                              ],
                            )
                          ]
                        ),),

                      onTap: () {itemFunctions[index]; print("Clicked item nr $index");}
                      ),
                    ),
                  );
                },
              );
            }
            return CircularProgressIndicator();
          })
      ),
);

}}

Редактировать: это один из экранов, который я хочу изменить на

class SuperKebab extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("Meniu Super Kebab"),
  ),
  body: Center(
    child: RaisedButton(
      onPressed: () {
        Navigator.pop(context);
      },
      child: Text('Revin!'),
    ),
  ),
);

}}

Редактировать: Кажется, что мой щелчок на элементах работает, но функции в List < Function >... не вызываются.

Это мой вывод журнала

enter image description here

Это мой Структура базы данных firebase:

enter image description here

Итак, в основном мой первый предмет - Antique, второй - Mediterana, а последний - SuperKebab

И я хочу, чтобы при нажатии на первый элемент (антиквариат), чтобы перейти к экрану «Античный», при нажатии на второй элемент я хочу, чтобы он перешел на экран Mediterana и т. Д.

Я думаю, что метод будет сделать одну функцию и заполнить ее данными из хранилища Firebase в зависимости от случая.

Любые идеи помогут мне. Заранее спасибо

1 Ответ

1 голос
/ 19 апреля 2020

Ваши функции будут определены в списке вручную или программно, а затем вы вызовете этот список, используя индекс из ListView.builder, например,

List<Function> itemfunctions = [
        (){print('Button Pressed!');},   
        (){Navigator.of(context).pop()},
        (){Navigator.popAndPushNamed(context, NewScreen.routeName)},
    ];
//Where you initialize this depends on whether you need context or not

  ListView.builder(
            shrinkWrap: true,
            itemCount: numbers.length,
            itemBuilder: (context, index) => Column(
              children: <Widget>[
                Text(
                  numbers[index].toString(),
                ),
                RaisedButton(
                  child: Text('$index number'),
                  onPressed: itemfunctions[index],
                )
              ],
            ),
          )
...