简体   繁体   English

Flutter:如何在两个小部件之间传递相同的数据?

[英]Flutter : How to pass the same data between two widgets?

I was building an app that shows the list of the teams by their name on search.我正在构建一个应用程序,该应用程序在搜索时按名称显示团队列表。 Now I want to navigate to the new screen and show the detail information about the team when clicked on the list items.现在我想导航到新屏幕并在单击列表项时显示有关团队的详细信息。

Here is the block of code for the List view:这是列表视图的代码块:

import 'package:fetchuser/team_details.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class TeamList extends StatefulWidget {
  String category;

  TeamList({this.category});

  _TeamListState createState() {
    return _TeamListState(category: category);
  }
}

class _TeamListState extends State<TeamList> {
  String category;

  _TeamListState({this.category});

  Future<List<dynamic>> fetchTeams() async {
    var result;
    try {
      result = await http.get(
          "https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${widget.category}");
      return json.decode(result.body)['teams'];
    } catch (e) {
      print(e);
    }
  }

  String _teamName(dynamic user) {
    return user['strTeam'];
  }

  String _location(dynamic user) {
    return user['strCountry'];
  }

  String _description(dynamic user){
    return user['strStadiumDescription'];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder<List<dynamic>>(
        future: fetchTeams(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
            return Center(
              child: Text("No Teams found"),
            );
          }
          if (snapshot.hasData) {
            return ListView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.all(8),
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {

                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => TeamDetails(teamList: TeamList(category: category,),)));
                    },
                    child: Card(
                      child: Column(
                        children: <Widget>[
                          ListTile(
                            leading: CircleAvatar(
                                radius: 30,
                                backgroundImage: NetworkImage(
                                    snapshot.data[index]['strTeamBadge'])),
                            title: Text(_teamName(snapshot.data[index])),
                            subtitle: Text(_location(snapshot.data[index])),
                          )
                        ],
                      ),
                    ),
                  );
                });
          }
          if (snapshot.hasError) {
            return Center(
              child: Text(snapshot.error),
            );
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
} 

And this is the block of code for the description page:这是描述页面的代码块:

import 'package:fetchuser/team_list.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class TeamDetails extends StatelessWidget {
  final TeamList teamList;

  const TeamDetails({ this.teamList});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back,color: Colors.black,),
          onPressed: (){
            Navigator.pop(context);
          },
        ),

      ),
      body: Column(children: <Widget>[
          Text(_description(snapshot.data[index]['strStadiumDescription'])),
      ],),
    );
  }
}  

I have just started working with flutter what should I do to make this work correctly?我刚刚开始使用 flutter 我应该怎么做才能使其正常工作?

You are passing data correctly but to get the data from the widget (TeamDetails) you have to get by using this code:您正在正确传递数据,但要从小部件(TeamDetails)获取数据,您必须使用以下代码获取:

widget.teamlist

You can call widget.teamlist to get the data and use it anywhere inside the widget.您可以调用 widget.teamlist 来获取数据并在小部件内的任何位置使用它。

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
You can pass snapshot.data[index] and receive with Map<String, dynamic>您可以传递snapshot.data[index]并使用Map<String, dynamic>接收
code snippet代码片段

Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => TeamDetails(
                        teamList: snapshot.data[index],
                      )));
...
class TeamDetails extends StatelessWidget {
  final Map<String, dynamic> teamList;

...
 Text("${teamList['strStadiumDescription']}"),

working demo工作演示

在此处输入图像描述

full code完整代码

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class TeamList extends StatefulWidget {
  String category;

  TeamList({this.category});
  @override
  _TeamListState createState() => _TeamListState();
}

class _TeamListState extends State<TeamList> {
  Future<List<dynamic>> fetchTeams() async {
    var result;
    try {
      result = await http.get(
          "https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${widget.category}");
      return json.decode(result.body)['teams'];
    } catch (e) {
      print(e);
    }
  }

  String _teamName(dynamic user) {
    return user['strTeam'];
  }

  String _location(dynamic user) {
    return user['strCountry'];
  }

  String _description(dynamic user) {
    return user['strStadiumDescription'];
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder<List<dynamic>>(
        future: fetchTeams(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.data == null) {
            return Center(
              child: Text("No Teams found"),
            );
          }
          if (snapshot.hasData) {
            return ListView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.all(8),
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => TeamDetails(
                                    teamList: snapshot.data[index],
                                  )));
                    },
                    child: Card(
                      child: Column(
                        children: <Widget>[
                          ListTile(
                            leading: CircleAvatar(
                                radius: 30,
                                backgroundImage: NetworkImage(
                                    snapshot.data[index]['strTeamBadge'])),
                            title: Text(_teamName(snapshot.data[index])),
                            subtitle: Text(_location(snapshot.data[index])),
                          )
                        ],
                      ),
                    ),
                  );
                });
          }
          if (snapshot.hasError) {
            return Center(
              child: Text(snapshot.error),
            );
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class TeamDetails extends StatelessWidget {
  final Map<String, dynamic> teamList;

  const TeamDetails({this.teamList});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0.0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: Column(
        children: <Widget>[
          Text("${teamList['strStadiumDescription']}"),
        ],
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: TeamList(
        category: "football",
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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