如何使用Flutter中“ for循环”生成的小部件导航到另一个页面?

时间:2019-07-24 03:09:54

标签: flutter dart

我正在测试这个Flutter项目,该项目从for循环生成电影列表:for (int i = 0; i < 3; i++) {...}. for循环的结果是3张卡,我想向其中添加onTap函数并导航到相应页面。

Github:https://github.com/devefy/Flutter-Streaming-Service-App-UI/blob/master/lib/main.dart

在222行填充后,我添加了一个带有onTap:(){}的ListTile() 小部件。这启用了卡的下半部分的水龙头小部件。

// Line 219 to 222
Padding(
padding: EdgeInsets.only(top: 3.0),
child: Text(i == 0 ? "Season 2" : ""),
),// Padding
ListTile(onTap: (){
debugPrint('${[i]} was tapped!');
//Navigator.push(context, route)

点击三张卡时的结果。

flutter: [0] was tapped!
flutter: [1] was tapped!
flutter: [2] was tapped!

我迷路的地方是如何根据我轻按的那张卡片实际导航到电影的详细信息页面。

感谢您的帮助...谢谢大家!

2 个答案:

答案 0 :(得分:0)

此类最佳做法是创建2个页面,一个电影列表和一个详细信息页面。

电影列表将遍历所有电影,然后点按将指向详细信息页面。关键是您可以在导航时将数据传递到详细信息页面。不管是电影的ID还是子弹,允许您获取特定数据,还是仅是列表的索引(举一个简单的示例)。

Navigator.push( context, MaterialPageRoute( builder: (context) => DetailScreen(todo: todos[index]),),);

这是关于待办事项列表和详细信息屏幕的示例。我会尝试运行此程序,以便您可以进一步理解我的意思。

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Todo {
  final String title;
  final String description;

  Todo(this.title, this.description);
}

void main() {
  runApp(MaterialApp(
    title: 'Passing Data',
    home: TodosScreen(
      todos: List.generate(
        20,
        (i) => Todo(
              'Todo $i',
              'A description of what needs to be done for Todo $i',
            ),
      ),
    ),
  ));
}

class TodosScreen extends StatelessWidget {
  final List<Todo> todos;

  TodosScreen({Key key, @required this.todos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(todos[index].title),
            // When a user taps the ListTile, navigate to the DetailScreen.
            // Notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailScreen(todo: todos[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  // Declare a field that holds the Todo.
  final Todo todo;

  // In the constructor, require a Todo.
  DetailScreen({Key key, @required this.todo}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // Use the Todo to create the UI.
    return Scaffold(
      appBar: AppBar(
        title: Text(todo.title),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Text(todo.description),
      ),
    );
  }
}

这是应用程序正在运行。

To Do Example

让我知道您是否有任何疑问!

答案 1 :(得分:0)

最后找到了我满意的解决方案。多亏了flutter_ui_challenge。

import 'package:flutter/material.dart';
import 'package:flutter_youtube/flutter_youtube.dart';


class YouTubeVideoList extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("YouTube Video List"),
        backgroundColor: Colors.lightBlue,
        elevation: 2,
        actions: <Widget>[
          Container(
            padding: EdgeInsets.all(10),
          )
        ],
      ),
      body: Lists(),
    );
  }
}

class Item {
  final String title;
  final String category;
  final String place;
  final Function onTap;
  final String image;

  Item(
      {this.title,
        this.category,
        this.place,
        this.onTap,
        this.image});
}

class Lists extends StatelessWidget {
  final List<Item> _data = [
    Item(
        onTap: playYoutubeVideo1,
        title: 'Gardens By the Bay',
        category: "Gardens",
        place: "Singapore",
        image: "https://images.pexels.com/photos/672142/pexels-photo-672142.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"),
    Item(
        onTap: playYoutubeVideo2,
        title: 'Singapore Zoo',
        category: "Parks",
        place: "Singapore",
        image: "https://images.pexels.com/photos/1736222/pexels-photo-1736222.jpeg?cs=srgb&dl=adult-adventure-backpacker-1736222.jpg&fm=jpg"),
    Item(
        onTap: playYoutubeVideo3,
        title: 'National Orchid Garden',
        category: "Parks",
        place: "Singapore",
        image: "https://images.pexels.com/photos/62403/pexels-photo-62403.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"),

  ];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: EdgeInsets.all(6),
      itemCount: _data.length,
      itemBuilder: (BuildContext context, int index) {
        Item item = _data[index];
        return GestureDetector(
          onTap: item.onTap,
          child: Card(
            elevation: 3,
            child: Row(
              children: <Widget>[
                Container(
                  height: 125,
                  width: 110,
                  padding:
                  EdgeInsets.only(left: 0, top: 10, bottom: 70, right: 20),
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: NetworkImage(item.image),
                          fit: BoxFit.cover)),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        item.title,
                        style: TextStyle(
                            color: Colors.deepOrange,
                            fontWeight: FontWeight.w700,
                            fontSize: 15),
                      ),
                      Text(
                        item.category,
                        style: TextStyle(fontSize: 12, color: Colors.black87),
                      ),
                      Text(
                        item.place,
                        style: TextStyle(fontSize: 10, color: Colors.black87),
                      ),
                      SizedBox(
                        height: 10,
                      ),

                    ],
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }

  var youtube = new FlutterYoutube();

 static playYoutubeVideo1() {
    FlutterYoutube.playYoutubeVideoByUrl(
      apiKey: "YOUR_API_KEY",
      videoUrl: "YOUTUBE_VIDEO_URL",
    );
  }

  static playYoutubeVideo2() {
    FlutterYoutube.playYoutubeVideoByUrl(
      apiKey: "YOUR_API_KEY",
      videoUrl: "YOUTUBE_VIDEO_URL",
    );
  }

  static playYoutubeVideo3() {
    FlutterYoutube.playYoutubeVideoByUrl(
      apiKey: "YOUR_API_KEY",
      videoUrl: "YOUTUBE_VIDEO_URL",
    );
  }
}