【问题标题】:How do I show the list on a different screen when Navigaor.pop used on the checkbox selection screen?当在复选框选择屏幕上使用 Navigator.pop 时,如何在不同的屏幕上显示列表?
【发布时间】:2020-04-08 13:29:04
【问题描述】:

我有一个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,
         ),
        ],
       );
      }
   }

【问题讨论】:

  • 请显示调用 Navigator.push 的位置。你可以利用返回值,不是吗?
  • @LoL 抱歉,现在我已经编辑了问题,您现在可以看看!谢谢

标签: flutter dart


【解决方案1】:

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

这是库

https://pub.dev/packages/event_bus

【讨论】:

    【解决方案2】:

    问题是当您弹出时,您上一页的状态没有更新。因此,在弹出时返回带有所选项目(来自复选框)的结果作为未来。一旦你弹出检查你是否得到任何结果,然后用新的状态重建用户界面。

    【讨论】:

      【解决方案3】:

      您可以使用push的返回值

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

      【讨论】:

      • 它没有帮助,数据只是没有返回到SecondPage
      【解决方案4】:

      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);
              },
            ),
          );
        }
      
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-18
        • 2021-07-29
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 2014-05-17
        • 1970-01-01
        相关资源
        最近更新 更多