【问题标题】:Flutter Navigator pop and async multiple fields dataFlutter Navigator 弹出和异步多字段数据
【发布时间】:2019-12-13 21:29:27
【问题描述】:

我有两个文本控制器,我想将两个文本控制器的数据从第二页传递到主屏幕,现在我的代码与一个变量一起工作正常,但我如何传递多个变量并使用它们。

Container(
                  margin: EdgeInsets.only(top:30),
                  child:RaisedButton(
                    onPressed: (){
                    Navigator.pop(context, titleController.text); //i want to pass multiple controllers here
                      print(titleController.text);

                    },
                    child: Text("Submit"),
                  ),
                ), 

用途: 这是我如何使用返回的数据。它适用于一个文本字段,但我希望传递多个字段。

_navigateAndDisplaySelection(BuildContext context) async {

 final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => SecondScreen()),
    );

              varlistSection.insert(0,
            listSectionMethod("$result", "hello from click", Icons.forward), //result contains one text field data, i want to use it for more
          );
          setState(() {});
  }

【问题讨论】:

  • 只需传递所有控制器文本的列表。
  • 那么我该如何使用它们,我试图让变量 result[] 包含数组,但它是错误的
  • 只需使用for 循环来获取所有文本。
  • 我该怎么做,我认为应该还有其他解决方案
  • @Fayakon,本杰明是对的。只需从您的第二页返回列表。如何使用检索到的列表取决于您在做什么。您打算如何在第一页中显示数据?

标签: flutter flutter-layout


【解决方案1】:

Fayakon,你为一个变量所做的看起来不错。当你像这样弹出它时,尝试从第二页返回一个字符串列表,

List<String> list = new List<String>();
list.add(titleController.text);
list.add(detailController.text);
Navigator.pop(context, list);

然后在你的第一页的功能中使用它,

_navigateAndDisplaySelection(BuildContext context) async {

 final result = await Navigator.push(context,
      MaterialPageRoute(builder: (context) => SecondScreen()),
    );

 varlistSection.insert(0,
            listSectionMethod(result[0], result[1], Icons.forward), //index would be for the data you wanna use
          );
 setState(() {});
}

【讨论】:

  • 我尝试了 listSectionMethod("$result", "$result[1]", Icons.forward),我将它们与 [1], $result[1] 放在一条线上是我传递它的方法的字符串类型。如果我键入诸如 listSectionMethod("title", "detail", Icons.forward) 之类的核心值,它将在顶部和描述底部显示标题,但是当我使用 $result 和代码中的索引时,一切都在一行中。
  • 知道了; listSectionMethod(result[0], result[1], Icons.forward),
  • 好吧,我不知道你在用什么,但很高兴它有帮助。不客气
【解决方案2】:
import 'package:flutter/material.dart';

void main() {
runApp(MaterialApp(home: MyApp(), debugShowCheckedModeBanner: 
false));
 }

类 MyApp 扩展 StatefulWidget { const MyApp({Key key}) : super(key: key);

@override
_MyAppState createState() => _MyAppState();
}

 class _MyAppState extends State<MyApp> {
 final GlobalKey<AnimatedListState> key = GlobalKey();
 GlobalKey<FormState> _formkey = GlobalKey<FormState>();

  List<String> _items = [];

   Future<String> showInfoDialog(BuildContext) async {
   return await showDialog(
    context: context,
    builder: (context) {
      final TextEditingController _textTitleController =
          TextEditingController();
      final TextEditingController _textDiscriptionController =
          TextEditingController();
      return AlertDialog(
        content: Form(
            key: _formkey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextFormField(
                  controller: _textTitleController,
                  validator: (value) {
                    return value.isEmpty ? "Invalid Field" : null;
                  },
                  decoration:
                      InputDecoration(hintText: "Enter Report Title"),
                ),
                TextFormField(
                  controller: _textDiscriptionController,
                  validator: (value) {
                    return value.isEmpty ? "Invalid Field" : null;
                  },
                  decoration:
                      InputDecoration(hintText: "Enter Report 
        Discrption"),
                )
              ],
            )),
        actions: <Widget>[
          TextButton(
              child: Text('submit'),
              onPressed: () {
                if (_formkey.currentState.validate()) {
                  Navigator.of(context)
                      .pop(_textTitleController.text.toString());
                }
              })
        ],
      );
    });
  }

  @override
   Widget build(BuildContext context) {
   return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: Scaffold(
      appBar: AppBar(
        title: Text('Alert'),
        backgroundColor: Colors.red[800],
        elevation: 2,
      ),
      body: AnimatedList(
        key: key,
        initialItemCount: _items.length,
        itemBuilder: (context, index, animation) {
          return _buildItem(
            _items[index],
            animation,
            index,
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          await showInfoDialog(context).then((value) {
            int i = _items.length > 0 ? _items.length : 0;
            _items.insert(i, value);
            key.currentState.insertItem(i);
          });
        },
      ),
    ));
  }

  Widget _buildItem(String items, Animation animation, int index) {
  return SizeTransition(
  sizeFactor: animation,
  child: Card(
    elevation: 2,
    child: ListTile(
      title: Text(
        items,
        style: TextStyle(fontWeight: FontWeight.w600),
      ),
      subtitle: Text("crush report in the main road"),
      leading: const Icon(
        Icons.warning_rounded,
        color: Colors.red,
        size: 30,
      ),

      // CircleAvatar(
      //   backgroundColor: Colors.red,
      // ),
      trailing: IconButton(
        icon: Icon(
          Icons.close,
          color: Colors.redAccent,
        ),
        onPressed: () {
          _removeItem(index);
        },
      ),
    ),
  ),
);
}

void _removeItem(int i) {
String removedItem = _items.removeAt(i);
AnimatedListRemovedItemBuilder builder = (
  context,
  animation,
) {
  return _buildItem(removedItem, animation, i);
};
key.currentState.removeItem(i, builder);
}

}

【讨论】:

  • 请不要只是转储一堆代码。相反,尝试解释您的代码在做什么,以及为什么这样可以解决问题。请记住,许多读者都是 Flutter 的新手,因此帮助他们理解这些概念将使这成为一个更有用的答案。在此过程中,请修正您的代码格式。
猜你喜欢
  • 2020-12-11
  • 2019-05-09
  • 2020-11-29
  • 2021-04-05
  • 2021-12-25
  • 1970-01-01
  • 2021-10-11
  • 2019-01-15
  • 2021-10-01
相关资源
最近更新 更多