skip to Main Content

Below List is in list.dart file, I want to use this (suppose: ‘place’: ‘Open Space’,) data from this List to a Text() in my main.dart file.

List<Map<String, dynamic>> hotelList = [
  {
    'image': 'one.png',
    'place': 'Open Space',
    'destination': 'London',
    'price': 25
  },
  {
    'image': 'two.png',
    'place': 'Global Will',
    'destination': 'London',
    'price': 40
  },
  {
    'image': 'three.png',
    'place': 'Tallest Building',
    'destination': 'Dubai',
    'price': 68
  },
];
child: Row(
  children: [
    Text(
      "???",
    )
  ],
),

2

Answers


  1. In your list.dart file you should put your list inside a class like this:

        class ListPlaces{
            List<Map<String, dynamic>> hotelList = [
          {
            'image': 'one.png',
            'place': 'Open Space',
            'destination': 'London',
            'price': 25
          },
          {
            'image': 'two.png',
            'place': 'Global Will',
            'destination': 'London',
            'price': 40
          },
          {
            'image': 'three.png',
            'place': 'Tallest Building',
            'destination': 'Dubai',
            'price': 68
          },
       ];
    }
    

    Actually for something so small you cold just declare the list in your main, but lets say it is only the beginning of your app and you will keep using list.dart.

    In main.dart, you can then declare inside your main class "ListPlaces places" to create a variable that have access to the class content, like this:

    class MyApp extends StatelessWidget {
       const MyApp({Key? key}) : super(key: key);
    
       ListPlaces places;
    
       @override
       Widget build(BuildContext context) {
         return MaterialApp(
           home: Container(
             child: Text(places.hotelList[0]['place']),
           ),
         );
       }
     }
    

    Note that you will have to use places.hotelList[0][‘place’], ‘places’ is the name of your variable created with ListPlaces (you class name), ‘hotelList’ is the name of your list, ‘[0]’ is the index of the location data in your list and ‘[‘place’] is the name of the field you want the content from.

    Sorry if I could’t make my self clear 🙁

    Login or Signup to reply.
  2. you can use following code

    Row(
          children: List.generate(
            hotelList.length,
            (index) {
              return Text('place : ${hotelList[index]['place']},');
            },
          ),
        )
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search