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

问题描述 投票:0回答:1

我正在建立一个应用程序,在搜索时按球队名称显示球队列表。现在我想导航到新的屏幕,并在点击列表项目时显示球队的详细信息。

这里是列表视图的代码块。

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,我应该怎么做才能使其正确工作?

flutter dart flutter-layout flutter-test flutter-widget
1个回答
0
投票

你正确地传递了数据,但是要从widget(TeamDetails)中获取数据,你必须使用这个代码。

widget.teamlist

你可以调用widget.teamlist来获取数据,并在widget中的任何地方使用它。


0
投票

你可以复制粘贴运行下面的完整代码 你可以通过以下代码来获取数据 snapshot.data[index] 并接受 Map<String, dynamic> 代码段

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

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

工作示范

enter image description here

全码

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",
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.