Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 屏幕之间的颤振传递数据_Flutter - Fatal编程技术网

Flutter 屏幕之间的颤振传递数据

Flutter 屏幕之间的颤振传递数据,flutter,Flutter,我正在开发一个使用flutter的预订应用程序。因此,这个想法是用户填写一个表单并将信息数据传递到另一个屏幕 下面的代码是表单屏幕 class Other extends StatefulWidget { final Trip trip; Other({Key key, this.trip}) : super(key: key); @override _OtherState createState() => _OtherState(); } class _Othe

我正在开发一个使用flutter的预订应用程序。因此,这个想法是用户填写一个表单并将信息数据传递到另一个屏幕

下面的代码是表单屏幕

    class Other extends StatefulWidget {
  final Trip trip;
  Other({Key key, this.trip}) : super(key: key);
  @override
  _OtherState createState() => _OtherState();
}

class _OtherState extends State<Other> {
  int _selectedIndex;
  List<String> _options = ['Regular', 'Hard Sleeper', 'Soft Sleeper'];
 
  DateTime _startDate = DateTime.now();
  DateTime _endDate = DateTime.now().add(Duration(days: 7));
  var adultNum = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var adultSel = 1;
  var childNum = [0, 1, 2, 3, 4, 5];
  var childSel = 0;
  var infantNum = [0, 1, 2];
  var infantSel = 0;
  var from = [
    'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
  ];
  var fromSel = 'Addis Ababa';
  var to = [
    'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
  ];
  var toSel = 'Djibouti';



  Future displayDateRangePicker(BuildContext context) async {
    final List<DateTime> picked = await DateRagePicker.showDatePicker(
      context: context,
      initialFirstDate: _startDate,
      initialLastDate: _endDate,
      firstDate: new DateTime(DateTime
          .now()
          .year),
      lastDate: new DateTime(DateTime
          .now()
          .year + 2),

    );
    if (picked != null && picked.length == 2) {
      setState(() {
        _startDate = picked[0];
        _endDate = picked[1];
      });
    }
  }

  Widget _buildChips() {
    List<Widget> chips = new List();

    for (int i = 0; i < _options.length; i++) {
      ChoiceChip choiceChip = ChoiceChip(
        selected: _selectedIndex == i,
        label: Text(_options[i], style: TextStyle(color: Colors.white)),
        //avatar: FlutterLogo(),
        elevation: 3,
        pressElevation: 5,
        //shadowColor: Colors.teal,
        backgroundColor: Colors.grey[400],
        selectedColor: Colors.lightGreen,
        onSelected: (bool selected) {
          setState(() {
            if (selected) {
              _selectedIndex = i;
            }
          });
        },
      );
      chips.add(choiceChip);

    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: chips,
    );

  }

  @override
  Widget build(BuildContext context) {
    final Trip newTrip = new Trip('regular', DateTime.now() , 'null', 1, 0, 0, DateTime.now(), 'null');
    return Container(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        child: Container(
          //height: 203,
          child: Column(
            children: [
              SizedBox(height: 15,),
              Container(
                //decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Container(
                      width: MediaQuery.of(context).size.width/2-19,
                      height: 60,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('From', style: TextStyle(
                            fontSize: 18,
                            color: Colors.grey
                          ),),
                          SizedBox(height: 0,),
                          Expanded(
                            child: DropdownButton<String>(
                              underline: Container(color: Colors.transparent),
                                items: from.map((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(value, style: TextStyle(
                                      fontSize: 18
                                    ),),
                                  );
                                }).toList(),
                              isExpanded: true,
                              isDense: false,
                              elevation: 5,
                              hint: Text('From'),
                                value: fromSel,
                                onChanged: (String newValue){
                                  setState(() {
                                    this.fromSel = newValue;
                                  });
                            }),
                          ),
                        ],
                      ),
                    ),
                    Container(height: 50, child: VerticalDivider(color: Colors.grey)),
                    Container(
                      width: MediaQuery.of(context).size.width/2-19,
                      height: 60,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('To', style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey
                          ),),
                          SizedBox(height: 0,),
                          Expanded(
                            child: DropdownButton<String>(
                                underline: Container(color: Colors.transparent),
                                items: to.map((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(value, style: TextStyle(
                                        fontSize: 18
                                    ),),
                                  );
                                }).toList(),
                                isExpanded: true,
                                isDense: false,
                                elevation: 5,
                                hint: Text('to'),
                                value: toSel,
                                onChanged: (String newValue){
                                  setState(() {
                                    this.toSel = newValue;
                                  });
                                }),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Divider(thickness: 1.0,),
              ),
              Container(
                height: 60,
                width: MediaQuery.of(context).size.width,
                //decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    InkWell(
                      child: Container(
                        // decoration: BoxDecoration(
                        //     border: Border.all(color: Colors.grey)
                        // ),
                        width: MediaQuery.of(context).size.width/2-19,
                        height: 60,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(top: 10, left: 10),
                              child: Text(
                                "Depart date",
                                style: TextStyle(
                                    fontSize: 18, color: Colors.black54),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 15, left: 10),
                              child: Text(
                                "${_startDate.day}/${_startDate
                                    .month}/${_startDate.year}",
                                style: TextStyle(
                                    fontSize: 15, color: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      ),
                        onTap: () async {
                          await displayDateRangePicker(context);
                        }
                    ),
                    Container(height: 50, child: VerticalDivider(color: Colors.grey)),
                    InkWell(
                      child: Container(
                        // decoration: BoxDecoration(
                        //     border: Border.all(color: Colors.grey)
                        // ),
                        width: MediaQuery.of(context).size.width/2-19,
                        height: 60,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(top: 10, left: 10),
                              child: Text(
                                "Return date",
                                style: TextStyle(
                                    fontSize: 18, color: Colors.black54),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 15, left: 10),
                              child: Text(
                                "${_endDate.day}/${_endDate.month}/${_endDate
                                    .year}",
                                style: TextStyle(
                                    fontSize: 15, color: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      ),
                      onTap: () async {
                        await displayDateRangePicker(context);
                      },
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Divider(thickness: 1.0,),
              ),
              Container(
                height: 60,
                width: MediaQuery.of(context).size.width,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Icon(Elusive.person, size: 20,),
                    Container(
                      width: 65,
                      height: 60,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        children: [
                          Text('Adult', style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey
                          ),),
                          Expanded(
                            child: DropdownButton<int>(
                                underline: Container(color: Colors.transparent),
                                items: adultNum.map((int value) {
                                  return DropdownMenuItem<int>(
                                    value: value,
                                    child: Text('$value', style: TextStyle(
                                        fontSize: 18
                                    ),),
                                  );
                                }).toList(),
                                isExpanded: true,
                                isDense: false,
                                elevation: 5,
                                value: adultSel,
                                onChanged: (int newValue){
                                  setState(() {
                                    this.adultSel = newValue;
                                  });
                                }),
                          ),
                        ],
                      ),
                    ),
                    Container(height: 50, child: VerticalDivider(color: Colors.grey)),
                    Icon(Elusive.person, size: 15,),
                    Container(
                      width: 65,
                      height: 60,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        children: [
                          Text('Child', style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey
                          ),),
                          Expanded(
                            child: DropdownButton<int>(
                                underline: Container(color: Colors.transparent),
                                items: childNum.map((int value) {
                                  return DropdownMenuItem<int>(
                                    value: value,
                                    child: Text('$value', style: TextStyle(
                                        fontSize: 18
                                    ),),
                                  );
                                }).toList(),
                                isExpanded: true,
                                isDense: false,
                                elevation: 5,
                                value: childSel,
                                onChanged: (int newValue){
                                  setState(() {
                                    this.childSel = newValue;
                                  });
                                }),
                          ),
                        ],
                      ),
                    ),
                    Container(height: 50, child: VerticalDivider(color: Colors.grey)),
                    Icon(Icons.child_friendly, size: 20,),
                    Container(
                      width: 70,
                      height: 60,
                      padding: EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        children: [
                          Text('Infant', style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey
                          ),),
                          Expanded(
                            child: DropdownButton<int>(
                                underline: Container(color: Colors.transparent),
                                items: infantNum.map((int value) {
                                  return DropdownMenuItem<int>(
                                    value: value,
                                    child: Text('$value', style: TextStyle(
                                        fontSize: 18
                                    ),),
                                  );
                                }).toList(),
                                isExpanded: true,
                                isDense: false,
                                elevation: 5,
                                value: infantSel,
                                onChanged: (int newValue){
                                  setState(() {
                                    this.infantSel = newValue;
                                  });
                                }),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Divider(thickness: 1.0,),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Container(
                  child: _buildChips(),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 45),
                child: Divider(thickness: 1.0,),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                child: MaterialButton(
                  onPressed: (){
                    widget.trip.from = fromSel;
                    widget.trip.to = toSel;
                    widget.trip.departDate = _startDate;
                    widget.trip.returnDate = _endDate;
                    widget.trip.adult = adultSel;
                    widget.trip.child = childSel;
                    widget.trip.infant = infantSel;
                    widget.trip.cabinClass = _selectedIndex;
                    
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) => Search(trip: newTrip,)));
                    //Navigator.of(context).pushNamed(Other.Search, arguments: newTrip);
                  },
                  minWidth: MediaQuery
                      .of(context)
                      .size
                      .width - 80,
                  height: 45,
                  shape:
                  RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  color: Colors.lightGreen,
                  splashColor: Colors.green,
                  child: Text(
                    "Search",
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              )

            ],
          ),
        ),
      ),
    );
  }
}
所以当我运行这个程序时,下面的错误会弹出

   ════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The setter 'from=' was called on null.
Receiver: null
Tried calling: from="Addis Ababa"

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _OtherState.build.<anonymous closure> (package:demo/BookingPages/other.dart:408:33)
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#fa011
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(167.3, 547.8)
  finalLocalPosition: Offset(127.3, 34.3)
  button: 1
  sent tap down
════════ 用手势捕捉异常═══════════════════════════════════════════════════════════════
处理手势时引发以下NoSuchMethodError:
对null调用了setter“from=”。
收件人:空
已尝试呼叫:from=“亚的斯亚贝巴”
引发异常时,这是堆栈:
#0 Object.noSuchMethod(省道:核心补片/对象补片。省道:51:5)
#1_OtherState.build。(套餐:演示/预订页面/其他。省道:408:33)
#2.InkResponseState.\u handleTap(包装:颤振/src/材料/墨水井。省道:993:19)
#3_inkrestate.build。(包装:颤振/src/材料/墨水井。省道:1111:38)
#4 GestureRecognizer.invokeCallback(包:flatter/src/signatures/recognizer.dart:183:24)
...
处理程序:“onTap”
识别器:TapGestureRecognizer#fa011
debugOwner:GestureDetector
国家:可能
赢得竞技场
最终位置:偏移量(167.3547.8)
财务状况:抵销(127.3,34.3)
按钮:1
发送轻敲

那么我该如何解决这个问题。

您还没有将
trip
参数传递给
Other
类。因此,当您尝试在
onPressed
方法中设置
from
参数时,您会出现错误。调用时,请尝试将非null的
trip
参数传递给
Other
类。

最好将注意力集中在您的问题上,使其更简单,并避免复制粘贴所有代码。问题出现在第一个(表单)屏幕上,而实际上它试图传递到第二个屏幕<代码>widget.trip.from=fromSel这是零件
    class Trip{
  String from;
  String to;
  DateTime departDate;
  DateTime returnDate;
  var cabinClass;
  var adult;
  var child;
  var infant;

  Trip(this.cabinClass,this.departDate,this.from,this.adult,this.child,this.infant,this.returnDate,this.to);
}
   ════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The setter 'from=' was called on null.
Receiver: null
Tried calling: from="Addis Ababa"

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _OtherState.build.<anonymous closure> (package:demo/BookingPages/other.dart:408:33)
#2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
#3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#fa011
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(167.3, 547.8)
  finalLocalPosition: Offset(127.3, 34.3)
  button: 1
  sent tap down