0

我对 Flutter 中的 Future builder 有疑问。它成功地从 api 获取信息但不显示它。当我从 api 打印和打印信息时,没问题,它显示电影名称没有任何问题。这是我的代码:

class Search extends StatefulWidget {
  final String value;
  Search({Key key, String this.value}) : super(key: key);
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  var title;

  Future getSearch({index}) async {
    http.Response response = await http.get(
        'https://api.themoviedb.org/3/search/company?api_key=6d6f3a650f56fd6b3347428018a20a73&query=' +
            widget.value);
    var results = json.decode(response.body);
    setState(() {
      this.title = results['results'];
    });
    return title[index]['name'];
  }

  getName(index) {
    return title[index]['name'];
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          backgroundColor: Color(0xff1d1d27),
          body: Column(
            children: [
              Expanded(
                  child: FutureBuilder(
                initialData: [],
                future: getSearch(),
                builder: (context, snapshot) {
                  return ListView.builder(itemBuilder: (context, index) {
                    Padding(
                      padding:
                          EdgeInsets.symmetric(horizontal: 30, vertical: 20),
                      child: Container(
                        color: Colors.white,
                        child: Text(getName(index).toString()),
                      ),
                    );
                  });
                },
              ))
            ],
          )),
    );
  }
}
4

1 回答 1

1

请使用这个code,它可以很好地获取名称并将它们显示在列表中,

import 'dart:convert';

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

class Search extends StatefulWidget {
  final String value;
  Search({Key key, String this.value}) : super(key: key);
  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  var title;
  var results;

  getSearch() async {
    http.Response response = await http.get(
        'https://api.themoviedb.org/3/search/company?api_key=6d6f3a650f56fd6b3347428018a20a73&query=' +
            widget.value);
    results = json.decode(
        response.body); //make it global variable to fetch it everywhere we need
    return results['results'][0]['name'];
  }

  getName(index) {
    return results['results'][index]['name'];
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          backgroundColor: Color(0xff1d1d27),
          body: Column(
            children: [
              Expanded(
                  child: FutureBuilder(
                // initialData: [],
                future: getSearch(),
                builder: (context, snapshot) {
                  String name =
                      snapshot.data; // to get the data from the getSearch
                  print(name);
                  if (snapshot.hasData) {
                    // if there is data then show the list
                    return ListView.builder(
                        itemCount: results['results']
                            ?.length, // to get the list length of results
                        itemBuilder: (context, index) {
                          return Padding(
                            padding: EdgeInsets.symmetric(
                                horizontal: 30, vertical: 20),
                            child: Container(
                              color: Colors.white,
                              child: Text(getName(index)
                                  .toString()), // pass the index in the getName to get the name
                            ),
                          );
                        });
                  } else {
                    // if there is no data or data is not loaded then show the text loading...
                    return new Text("Loading...",
                        style: TextStyle(fontSize: 42, color: Colors.white));
                  }
                },
              ))
            ],
          )),
    );
  }
}

PS
学习Futurebuilder的基础知识可以看这篇文章了解更多

我已经评论了代码以向您解释更多。

于 2020-12-30T12:38:22.947 回答