【问题标题】:Flutter : How to pass the same data between two widgets?Flutter:如何在两个小部件之间传递相同的数据?
【发布时间】: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'])),
      ],),
    );
  }
}  

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

【问题讨论】:

    标签: flutter dart flutter-layout flutter-test flutter-widget


    【解决方案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",
            ),
          );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-22
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        • 2018-08-01
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多