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

Posted

技术标签:

【中文标题】Flutter:如何在两个小部件之间传递相同的数据?【英文标题】:Flutter : How to pass the same data between two widgets? 【发布时间】:2020-10-07 06:11:49 【问题描述】:

我正在构建一个应用程序,该应用程序在搜索时按名称显示团队列表。现在我想导航到新屏幕并在单击列表项时显示有关团队的详细信息。

这是列表视图的代码块:

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());
        ,
      ),
    );
  
 

这是描述页面的代码块:

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'])),
      ],),
    );
  
  

我刚刚开始使用颤振,我应该怎么做才能使其正常工作?

【问题讨论】:

【参考方案1】:

您正在正确传递数据,但要从小部件 (TeamDetails) 获取数据,您必须使用以下代码获取:

widget.teamlist

您可以调用 widget.teamlist 来获取数据并在小部件内的任何位置使用它。

【讨论】:

【参考方案2】:

您可以在下面复制粘贴运行完整代码 您可以通过snapshot.data[index] 并通过Map&lt;String, dynamic&gt; 接收 代码sn-p

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

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

工作演示

完整代码

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",
      ),
    );
  

【讨论】:

以上是关于Flutter:如何在两个小部件之间传递相同的数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何在有状态小部件之间传递随机数据?

如何在 Flutter 中删除两个容器之间的空间?

Flutter:多个小部件使用相同的 GlobalKey

将数据从 Flutter Stream 传递到小部件

Flutter:如何在构造函数中传递值,以便我可以重用我的小部件?

Flutter - 如何对齐(小部件)孙小部件与孩子相同