我如何在Flutter中的文本小部件中显示API响应

mklgxw1f  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(130)

**我正在使用get方法接收数据,这已经成功完成,现在我如何在另一个类的文本小部件中显示这些响应?**这是我使用get方法的API类:

const apiHost = 'andruxnet-random-famous-quotes.p.rapidapi.com';
const apiUrl = 'https://andruxnet-random-famous-quotes.p.rapidapi.com/';
const apiKey = '14b77a3e77msh224667c7b07c6edp170846jsn2144e4d9735f';

class Quote {
  static Future getQuote() async {
    var client = http.Client();
    var uri = Uri.parse(apiUrl);
    var response = await client.get(
      uri,
      headers: {'X-RapidAPI-Key': apiKey, 'X-RapidAPI-Host': apiHost},
    );
    if(response.statusCode == 200){
      var json = response.body;
      return getQuoteFromJson(json);
    }
    else {
      throw Exception(response.reasonPhrase);
    }
  }
}

此为型号:

import 'dart:convert';

List<GetQuote> getQuoteFromJson(String str) => List<GetQuote>.from(json.decode(str).map((x) => GetQuote.fromJson(x)));

String getQuoteToJson(List<GetQuote> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class GetQuote {
    GetQuote({
        required this.quoteText,
        required this.author,
    });

    String quoteText;
    String author;

    factory GetQuote.fromJson(Map<String, dynamic> e) => GetQuote(
        quoteText: e["quote"],
        author: e["author"],
    );

    Map<String, dynamic> toJson() => {
        "quote": quoteText,
        "author": author,
    };
}

界面代码如下:

class QuotePage extends StatefulWidget {
  const QuotePage({super.key});

  @override
  State<QuotePage> createState() => _QuotePageState();
}

class _QuotePageState extends State<QuotePage> {

 List<GetQuote> quote = [];

@override
void initState() {
  super.initState();
  getData();
}

getData() async{
  final response = await Quote.getQuote();

  setState(() {
    quote = response;
  });
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: backgroundColor,
        centerTitle: true,
        title: const Text(
          'Quote App',
          style: kAppBarTextStyle,
        ),
      ),
      body: Stack(
        alignment: Alignment.center,
        children: [
          PositionedWidget(
            top: 50,
            width: 250.0,
            height: 500,
            child: Container(
              decoration: BoxDecoration(
                color: smallContainerColor,
                borderRadius: BorderRadius.circular(10.0),
              ),
            ),
          ),
          PositionedWidget(
            top: 60,
            width: 300.0,
            height: 500,
            child: Container(
              decoration: BoxDecoration(
                color: mediumContainerColor,
                borderRadius: BorderRadius.circular(10.0),
              ),
            ),
          ),
          PositionedWidget(
          top: 70,
          width: 350.0,
          height: 500,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.0),
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: AssetImage(kContainerImage),
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children:const [
                  TextContainer(
                    text: ('Hello'),
                    style: kQuoteTextStyle,
                    padding: kQuotePadding,
                  ),
                  Align(
                    alignment: Alignment.bottomRight,
                    child: TextContainer(
                      text: 'Author\'s name',
                      style: kAuthornameTextStyle,
                      padding: kAuthornamePadding,
                    ),
                  )
                ],
              ),
            ),
          ),
            ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton:  FloatingActionButton.extended(
        backgroundColor: kFloatingActionButtonColor,
        onPressed: getData,
        label: const Text(
          'Next Quote',
          style: kFloatingActionTextStle,
        ),
      ),
    );
  }
}

我正在使用get方法接收数据,这已经成功完成了,现在我如何在另一个类的文本小部件中显示这些响应?

k5ifujac

k5ifujac1#

要在文本小部件中显示API响应,您应该使用API响应中的实际数据替换硬编码文本。以下是如何修改_QuotePageState类和包含文本小部件的Column:
首先,用一个空的GetQuote对象而不是一个空的列表初始化你的quote变量。这将允许你在文本小部件中显示一个引用及其作者。

GetQuote quote = GetQuote(quoteText: '', author: '');

  // ...
}

接下来,修改getData方法以处理响应不是列表的情况:

final response = await Quote.getQuote();

  setState(() {
    if (response is List<GetQuote>) {
      quote = response[0];
    } else {
      quote = response;
    }
  });
}

最后,更新Column中的Text小部件,以显示quote对象的quoteText和author属性:

Column(
  mainAxisAlignment: MainAxisAlignment.spaceBetween,
  children: [
    TextContainer(
      text: quote.quoteText,
      style: kQuoteTextStyle,
      padding: kQuotePadding,
    ),
    Align(
      alignment: Alignment.bottomRight,
      child: TextContainer(
        text: quote.author,
        style: kAuthornameTextStyle,
        padding: kAuthornamePadding,
      ),
    ),
  ],
),

现在,API响应将显示在文本小部件中。

相关问题