You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter技术问询:如何在RestaurantScreen类访问外部定义的restaurantList

How to Access restaurantList Items in RestaurantScreen

Hey there! Let's sort out how to access your restaurantList entries from the RestaurantScreen class. I'll walk you through a few practical approaches, from the simplest to the most scalable:


1. Directly Import the File with restaurantList

Since your restaurantList is defined as a top-level variable in the file where RestaurantWidget lives, you can just import that file into RestaurantScreen's dart file to use it directly.

Step-by-Step:

  1. Add the import statement to your RestaurantScreen file:
import 'package:projectfooddelivery/Src/widgets/restaurant_widget.dart'; // Replace with your actual path to RestaurantWidget
  1. Now you can reference any item in restaurantList directly. For example, replace hardcoded details with dynamic data from the list:
class RestaurantScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Use the first restaurant as an example
    final selectedRestaurant = restaurantList[0];
    
    return Scaffold(
      body: Container(
        width: 400,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                Image.asset(
                  "images/${selectedRestaurant.image}", // Dynamic image path
                  fit: BoxFit.cover,
                ),
                Positioned(
                  child: IconButton(
                    icon: Icon(Icons.keyboard_arrow_left,size: 40,color: Colors.white,),
                    onPressed: (){},
                  ),
                  top: 15,
                )
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 14, left: 14, right: 14),
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          selectedRestaurant.restaurantName, // Dynamic restaurant name
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 18,
                          ),
                        ),
                        Text(
                          selectedRestaurant.distance, // Dynamic distance
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                    // ... existing star rating code
                    Align(
                      alignment: Alignment.topLeft,
                      child: Text(selectedRestaurant.location), // Dynamic location
                    ),
                    // ... rest of your column code
                  ]
                )
              ),
            )
          ],
        ),
      ),
    );
  }
}

Global variables work for small apps, but passing the specific restaurant the user tapped directly to RestaurantScreen makes your code more maintainable and flexible (you won't be locked into using just the first list item!).

Step 1: Update RestaurantScreen to accept a Restaurant parameter

class RestaurantScreen extends StatelessWidget {
  final Restaurant selectedRestaurant; // Add this parameter

  // Constructor with required parameter
  const RestaurantScreen({Key? key, required this.selectedRestaurant}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: 400,
        child: Column(
          children: <Widget>[
            Stack(
              children: <Widget>[
                Image.asset(
                  "images/${selectedRestaurant.image}",
                  fit: BoxFit.cover,
                ),
                // ... existing back button code
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 14, left: 14, right: 14),
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text(
                          selectedRestaurant.restaurantName,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 18,
                          ),
                        ),
                        Text(
                          selectedRestaurant.distance,
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                    // ... existing star rating code
                    Align(
                      alignment: Alignment.topLeft,
                      child: Text(selectedRestaurant.location),
                    ),
                    // ... rest of your column code
                  ]
                )
              ),
            )
          ],
        ),
      ),
    );
  }
}

Step 2: Add Navigation in RestaurantWidget to pass the selected Restaurant

Wrap the list item container in a GestureDetector so users can tap to navigate:

// Inside RestaurantWidget's itemBuilder:
return Padding(
  padding: const EdgeInsets.all(8.0),
  child: GestureDetector(
    onTap: () {
      // Navigate to RestaurantScreen and pass the tapped restaurant
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => RestaurantScreen(selectedRestaurant: restaurantList[index]),
        ),
      );
    },
    child: Container(
      // ... your existing container decoration and child code
    ),
  ),
);

3. Use State Management (For Larger Apps)

If your app has multiple screens that need access to shared data like restaurantList, using a state management library like Provider, Riverpod, or GetX is a great choice. It centralizes your data so any screen can access it without passing parameters around.

Here's a quick example with Provider:

  1. Create a RestaurantProvider class:
import 'package:flutter/material.dart';
import 'package:projectfooddelivery/Src/models/restaurant.dart';

class RestaurantProvider extends ChangeNotifier {
  final List<Restaurant> restaurantList = [
    Restaurant(image:"kfcloja.jpg",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
    Restaurant(image:"dominos.jpg",distance: "0.9 miles away",location:"Downtown",restaurantName: "Dominos"),
    Restaurant(image:"kfclogo.png",distance: "2 miles away",location:"Shoprite do magoanine",restaurantName: "KFC"),
  ];
}
  1. Wrap your app with ChangeNotifierProvider in main.dart:
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => RestaurantProvider(),
      child: MyApp(),
    ),
  );
}
  1. Access the list in RestaurantScreen:
class RestaurantScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final restaurantProvider = Provider.of<RestaurantProvider>(context);
    // You can also track a selected restaurant ID in the provider for dynamic selection
    final selectedRestaurant = restaurantProvider.restaurantList[0];

    return Scaffold(
      // ... your existing UI code using selectedRestaurant
    );
  }
}

内容的提问来源于stack exchange,提问作者Valdo Amaral

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:32:37