简体   繁体   中英

RangeError (index): Index out of range: no indices are valid: 0 - Flutter

I'm new to flutter. When I'm trying to add list data to the widget RealAppcard of Text the list data is '${extractRooms[0]}' I'm getting this error RangeError (index): Index out of range: no indices are valid: 0 but without this data added everything is working what am I doing wrong here?

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gs/card_real_app.dart';
import 'package:gs/homescreen.dart';
import 'package:gs/network.dart';
import 'package:gs/pic_model.dart';
import 'package:gs/reusable_card.dart';
import 'package:dotted_border/dotted_border.dart';

import 'Custom_textfield.dart';
import 'order.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

import 'ordertile.dart';

const cardinactiveColor = Color(0xFF0a1529);
const cardActivecolor = Color(0xFFffb700);
var orderData;
// List<Order> orders = <Order>[];
List<Order> OrdersItems = [];
List<dynamic> feedbacks = [];
List<dynamic> pics = [];
late final String? picData;
late final String? statusData;

List<dynamic> filteredOrdersItems = [];
List<dynamic> feedbpics = [];
// final assetController = TextEditingController();

String currentSearch = '';
// String? statusOrder;
// String? picOrder;
// String? myStr = 'shalom';
List<dynamic> extractRooms = [];
List<dynamic> extractStatus = [];
List<dynamic> extractType = [];
List<dynamic> extractMap = [];
dynamic getRooms() {
  filteredOrdersItems.forEach((item) {
    extractRooms.insert(0, item.rooms);
    // print('${item.pic}');
  });
}

dynamic getType() {
  filteredOrdersItems.forEach((item) {
    extractType.insert(0, item.type);
    // print('${item.pic}');
  });
}

dynamic getSatausData() {
  filteredOrdersItems.forEach((item) {
    extractStatus.insert(0, item.status);
    // print('${item.pic}');
  });
}

dynamic getPicData() {
  filteredOrdersItems.forEach((item) {
    extractMap.insert(0, item.pic);
    // print('${item.pic}');
  });
}

var data;
var parsedJsonText = jsonDecode(data);

class searchScreen extends StatefulWidget {
  // firstScreen({Key? key}) : super(key: key);

  @override
  State<searchScreen> createState() => _searchScreenState();
}

class _searchScreenState extends State<searchScreen> {
  @override
  void initState() {
    super.initState();

    getOrders().then((
      OrderItems,
    ) {
      setState(() {
        // this.OrderItems = OrderItems;
        // filteredOrdersItems = OrderItems;
      });
    });
  }

  // void initState() {
  //   super.initState();

  //   getOrders().then((
  //     feedbackItems,
  //   ) {
  //     setState(() {
  //       // this.feedbackItems = feedbackItems;
  //       // this.filteredFeedbackItems = feedbackItems;
  //     });
  //   });
  // }

  // List<OrderModel> orders = <OrderModel>[];
  Color cardColor = cardinactiveColor;

  void updateColor() {
    if (cardColor == cardinactiveColor) {
      cardColor = cardActivecolor;
    } else {
      cardColor = cardinactiveColor;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // ignore: prefer_const_literals_to_create_immutables
          Container(
            height: 400,
            color: Color(0xFF0a1529),
            child: Column(
              children: [
                const Icon(
                  Icons.real_estate_agent_outlined,
                  color: Colors.white,
                  size: 80,
                ),

                // data: Icons.real_estate_agent_outlined,

                SizedBox(height: 5),
                Text(
                  'ברוכים הבאים לאפליקצית חיפוש נכסים',
                  style: TextStyle(
                    fontSize: 20.0,
                    color: Colors.blue,
                  ),
                ),
                SizedBox(height: 15),
                CustomTextField(
                  data: Icons.search,
                  // controller: null,
                  hintText: 'חיפוש נכס',
                  enabled: true,

                  // controller: assetController,
                ),

                SizedBox(height: 15),

                DottedBorder(
                  color: Color(0xFFffb700),
                  strokeWidth: 1,
                  child: Card(
                    color: Colors.transparent,
                    elevation: 0,
                    child: Container(
                      width: 400,
                      height: 140,
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: const [
                              Padding(
                                padding: EdgeInsets.all(10.0),
                                child: Icon(
                                  FontAwesomeIcons.crown,
                                  // Icons.workspace_premium,
                                  color: Color(0xFFffb700),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.all(10.0),
                                child: Text(
                                  'מיוחדים',
                                  style: TextStyle(
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Text(
                            'מוזמנים להתנסות במערכת הנפלאה',
                            style: TextStyle(
                              color: Color(0xFF8d8e98),
                            ),
                          ),
                          SizedBox(height: 20),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              GestureDetector(
                                onTap: () {},
                                child: Card(
                                  color: cardColor,
                                  child: Container(
                                    child: Row(
                                      children: [
                                        ButtonTheme(
                                          minWidth: 30.0,
                                          height: 15.0,
                                          child: RaisedButton(
                                              color: Colors.amber,
                                              child: Text(
                                                'בצעו חיפוש',
                                                style: TextStyle(
                                                  fontSize: 20,
                                                ),
                                              ),
                                              onPressed: () async {
                                                feedbacks = await getOrders();
                                                // pics = await getPic();

                                                // feedbpics =
                                                //     pics.where((element) {
                                                //   return element.id ==
                                                //       currentSearch;
                                                // }).toList();
                                                // print(feedbpics);
                                                print(feedbacks);

                                                filteredOrdersItems =
                                                    feedbacks.where((element) {
                                                  return element.address ==
                                                      currentSearch;
                                                }).toList();
                                                filteredOrdersItems
                                                    .forEach((item) {
                                                  print('${item.pic}');
                                                });
                                                // picData = getStatus();
                                                // statusData = getPic();
                                                // print('pic $picData');
                                                // print('status $statusData');
                                                // getPic();

                                                getPicData();
                                                getType();
                                                getSatausData();
                                                getRooms();

                                                print(
                                                    'checking ${filteredOrdersItems[0]}');
                                                print(
                                                    'list map${filteredOrdersItems}');
                                                print('list $extractMap');
                                                print(extractMap[0]);
                                                print(
                                                    'status ${extractStatus[0]}');
                                                print(
                                                    'rooms ${extractRooms[0]}');
                                                // print(
                                                //     'status ${extractMapStatus}');
                                                setState(() {});
                                              }),
                                        ),
                                        // Text(
                                        //   'בדקו עכשיו',
                                        //   style: TextStyle(
                                        //     color: Colors.white,
                                        //   ),
                                        // ),
                                        Icon(
                                          FontAwesomeIcons.arrowRight,
                                          // Icons.workspace_premium,
                                          color: Color(0xFFffb700),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(24),
            ),
            color: Colors.white,
            elevation: 5,
            child: Container(
                width: 500,
                height: 500,
                decoration:
                    BoxDecoration(borderRadius: BorderRadius.circular(25)),
                child: Column(
                  children: [
                    // Text('${feedbpics[0]}'),
                    if (filteredOrdersItems.isEmpty) ...{
                      Text(
                        "לא נמצאו תוצאות נסו שנית",
                        style: TextStyle(
                          fontSize: 20,
                        ),
                      ),
                    } else ...{
                      Text(
                        '${extractType[0]}',
                        style: TextStyle(
                          fontSize: 20,
                        ),
                      ),
                      SizedBox(height: 20),
                      Card(
                        elevation: 8,
                        child: Image.network(
                          '${extractMap[0]}',
                          width: 200,
                          height: 100,
                        ),
                      ),
                    },
                    // SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          'כתובת מלאה',
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFFA435F0),
                          ),
                        ),
                        Text('ניקוד נכס'),
                      ],
                    ),

                    // SizedBox(height: 10),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        realAppCard(
                          text: 'חדרים',
                          quantity: '${extractRooms[0]}',
                        ),
                        realAppCard(
                          text: 'גודל דירה',
                          quantity: '120',
                        ),
                        realAppCard(
                          text: 'מחיר',
                          quantity: '1.5',
                        ),
                      ],
                    ),
                    SizedBox(height: 10),
                    Card(
                      color: Colors.green,
                      elevation: 10,
                      child: Container(
                        width: 100,
                        height: 30,
                        child: Text(
                          'status',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 20,
                          ),
                        ),
                      ),
                    ),

                    SizedBox(height: 5),
                    Center(
                      child: Text(
                        ''' 
       הרשות פרסמה את ממצאי התחקיר שערכה על הרג כתבת אל ג'זירה, 
ממנו עולה שהחיילים ירו בה בכוונה, למרות שראו שמדובר בעיתונאית.
                      לטענת התובע, הקליע, שהשימוש בו לא היה חוקי  
                      ''',
                        textAlign: TextAlign.center,
                      ),
                    ),
                    SizedBox(height: 5),
                    Card(
                      elevation: 2,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(10),
                              topRight: Radius.circular(10)),
                          side: BorderSide(width: 1, color: Colors.blueGrey)),
                      child: ListTile(
                        leading: Icon(Icons.message_outlined),
                        trailing: Text('משה כהן'),
                        title: Text('052-3567104'),
                      ),
                    ),
                    SizedBox(height: 5),
                    ElevatedButton(
                      onPressed: null,
                      child: Text('שליחת ווטסאפ'),
                    ),
                  ],
                )),

            // Center(
            //   child: Container(
            //     width: 300,
            //     child: TextField(
            //       decoration: const InputDecoration(
            //           border: OutlineInputBorder(), hintText: 'הקלידו הזמנה'),
            //       onChanged: (String newstr) {
            //         currentSearch = newstr;
            //         // print('first: ${currentSearch}');
            //         // print(newstr);
            //         // feedbackItems.forEach((element) {
            //         //   print(element.status);
            //         // });
            //       },
            //     ),
            //   ),
            // ),
            // SizedBox(height: 20),
            // ButtonTheme(
            //   minWidth: 200.0,
            //   height: 30.0,
            //   child: RaisedButton(
            //       color: Colors.amber,
            //       child: Text(
            //         'בצעו חיפוש',
            //         style: TextStyle(
            //           fontSize: 20,
            //         ),
            //       ),
            //       onPressed: () async {
            //         feedbacks = await getOrders();
            //         print(feedbacks);

            //         filteredOrdersItems = feedbacks.where((element) {
            //           return element.id == currentSearch;
            //         }).toList();
            //         print(filteredOrdersItems);
            //         setState(() {});
            //       }),
            // ),
            // SizedBox(height: 10),
            // ignore: sdk_version_ui_as_code
          )
        ],
      ),
    );
  }
}

Future<List<dynamic>> getOrders() async {
  String url =
      'https://script.google.com/macros/s/AKfycbyT3xsBV2nrxgCotCA8-hyZ1DNTNt1ET0wuKilQZr29ac8pbpXMk7nMrCnz2_7NPW1j/exec';

  var response = await http.get(Uri.parse(url));

  var jsonData = convert.jsonDecode(response.body) as List;

  String data = response.body;

  // var parsedJson = json.decode(response.body);
  // var orderModel = jsonDecode(data)[0]['pic'];

  // print('this is my natun ${orderModel}');
  // print('response body ${data}');
  // print(jsonData);

  return jsonData.map((json) => Order.fromJson(json)).toList();

  // for (var order in jsonData) {
  //   OrdersItems.add(Order(order['id'], order['name'], order['status']));
  //   OrdersItems.forEach((element) {
  //     print("id : ${element.id}");
  //   });
  // }

  // // filteredOrdersItems =
  // //     OrdersItems.where((ord) => ord['id']  == 'test').toList();

  // print(OrdersItems[1].id);
  // print(OrdersItems);
  // print(filteredOrdersItems);

  // return OrdersItems;
}

// Future<List<dynamic>> getPic() async {
//   String url =
//       'https://script.google.com/macros/s/AKfycbz12UnYLSmxvwGdeUH2EI7VQ8AnLMACE6IEy3bl3TcmhnyWa0Wmfxxr17swWWXCoXqd/exec';

//   var response = await http.get(Uri.parse(url));

//   var jsonData = convert.jsonDecode(response.body) as List;
//   // print(jsonData);

//   return jsonData.map((json) => Pic.fromJson(json)).toList();
// }

if you getting the error, it means one of the extractRoom throwing this is empty, so what you can do it check if the extractRoom is not empty before displaying its content.

realAppCard(
  text: 'מחיר',
  quantity: extractRoom.isNotEmpty ? extractRoom[0] : '0.0',
),

this will do the work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM