在复选框选择屏幕上使用Navigaor.pop时,如何在另一个屏幕上显示列表?

时间:2019-12-16 04:36:39

标签: flutter dart

我有一个CheckBox项目选择屏幕(在浮动按钮中触发Navigator.push时打开)以检查我喜欢的项目,并且我希望这些项目在使用Navigator.pop时显示在屏幕上(当点击浮动按钮时)返回到其原始屏幕。但是我无法做到这一点,我认为list.map将在这里使用,但是我能够正确实现它。任何帮助都非常感谢。

您可以检查整个代码here

我遇到问题的代码:

// CheckBox Item Selection Screen!
class FavoriteList extends StatefulWidget {
@override
_FavoriteListState createState() => _FavoriteListState();
}

class _FavoriteListState extends State<FavoriteList> {

final Set _saved = Set();

@override
Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(title: Text('Add to Favorites!'), centerTitle:  true, backgroundColor: Colors.red),
  // backgroundColor: Colors.indigo,
  body: SafeArea(
          child: ListView.builder(
      itemCount: 53,
      itemBuilder: (context, index) {
        return CheckboxListTile(
          activeColor: Colors.red,
          checkColor: Colors.white,
          value: _saved.contains(index),
             onChanged: (val) {
              setState(() {
              if(val == true){
                _saved.add(index);
              } else{
                _saved.remove(index);
              }
            });
          },
          title: Row(
            children: <Widget>[
              Image.asset('lib/images/${images[index]}'),
              SizedBox(width: 10,),
              Text(nameOfSite[index]),
            ],
          ),
        );
      },
    ),
  ),
  floatingActionButton: FloatingActionButton(foregroundColor: Colors.red,
  child: Icon(Icons.check),
    onPressed: (){
      Navigator.pop(context, _saved); // Navigator.pop
    },
  ),
);
    }
   }

这里是原始屏幕,我想return_saved列表(我使用Set来避免重复)

class SecondPage extends StatefulWidget {
@override
_SecondPageState createState() => _SecondPageState();
}


class _SecondPageState extends State<SecondPage> {
@override
Widget build(BuildContext context) {
  return 
   // if the `_saved` list contains something return the "_saved" list from 
   the CheckBox item selection screen, if not then 
    return  Column(
           mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
        Text(
           'Add Your Favorite Sites Here!❤',
           style: TextStyle(color: Colors.white),
           ),
           Container(
            child: Icon(Icons.favorite, size: 150, color: Colors.blue[100]),
          ),
          SizedBox(height: 250),
            FloatingActionButton(
             onPressed: () {
               Navigator.push( //Navigator.push is here!
                  context,
                   MaterialPageRoute(
            builder: (context) => FavoriteList(),
                ),
              );
           },
            child: Icon(Icons.add),
          foregroundColor: Colors.blue,
         ),
        ],
       );
      }
   }

4 个答案:

答案 0 :(得分:1)

您可以使用Event_Bus在屏幕之间传递数据。

这是lib

https://pub.dev/packages/event_bus

答案 1 :(得分:0)

问题是当您弹出时,上一页的状态未更新。因此,弹出时返回带有选定项目(从复选框)的结果作为将来。弹出后,检查是否有任何结果,然后以新状态重建ui。

答案 2 :(得分:0)

您可以利用push的返回值

// _SecondPageState
FloatingActionButton(
  onPressed: () async {
    Set saved = await Navigator.push<Set>(
      context,
      MaterialPageRoute(builder: (context) => FavoriteList()),
    );
    setState(() {
      // do something
    });
  },
),

答案 3 :(得分:0)

Navigator.push()具有返回值,您可以在调用Navigator.pop(时传递想要的内容

这是您应注意的主要代码:

SecondPage 类中的

FloatingActionButton(
  onPressed: () async {
    final Set indices = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => FavoriteList(indices: _indices), // you may wanna passing in what you have checked.
      ),
    );

    if (indices != null) {
      // do what you want, like setState()
      setState(() {
        final List tempIndices = _indices;
        tempIndices.addAll(indices);
        _indices = tempIndices.toSet().toList();
      });
    }
  },
),

FavoriteList 类中的

floatingActionButton: FloatingActionButton(
  onPressed: () {
    Navigator.pop(context, _saved);
  },
),

如果要检查完整的代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Navigator Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SecondPage(),
    );
  }
}

class SecondPage extends StatefulWidget {

  @override
  _SecondPageState createState() => _SecondPageState();

}

class _SecondPageState extends State<SecondPage> {

  List _indices = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 25.0, vertical: 75.0),
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Add Your Favorite Sites Here!',
              style: TextStyle(
                color: Colors.black,
                fontSize: 24.0,
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _indices.length,
                itemBuilder: (context, index) {
                  return Center(
                    child: Text(
                      '${_indices[index]}',
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 24.0,
                      ),
                    ),
                  );
                },
              ),
            ),
            FloatingActionButton(
              onPressed: () async {
                final Set indices = await Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => FavoriteList(indices: _indices),
                  ),
                );

                if (indices != null) {
                  setState(() {
                    final List tempIndices = _indices;

                    tempIndices.addAll(indices);

                    _indices = tempIndices.toSet().toList();
                  });
                }
              },
              child: Icon(
                Icons.add,
                color: Colors.white,
              ),
              foregroundColor: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }

}

class FavoriteList extends StatefulWidget {

  FavoriteList({
    Key key,
    this.indices,
  }) : super(key: key);

  final List indices;

  @override
  _FavoriteListState createState() => _FavoriteListState();

}

class _FavoriteListState extends State<FavoriteList> {

  final Set _saved = Set();

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

    _saved.addAll(widget.indices);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Add to Favorites!'),
        centerTitle: true,
        backgroundColor: Colors.red,
      ),
      body: SafeArea(
        child: ListView.builder(
          itemCount: 53,
          itemBuilder: (context, index) {
            return CheckboxListTile(
              activeColor: Colors.red,
              checkColor: Colors.white,
              value: _saved.contains(index),
              onChanged: (val) {
                setState(() {
                  if (val == true) {
                    _saved.add(index);
                  } else {
                    _saved.remove(index);
                  }
                });
              },
              title: Row(
                children: <Widget>[
                  Text('$index'),
                ],
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        foregroundColor: Colors.red,
        child: Icon(Icons.check),
        onPressed: () {
          Navigator.pop(context, _saved);
        },
      ),
    );
  }

}