将Flask API中的JSON数据解析为抖动列表 [英] Parse json data from flask api to flutter lists

查看:73
本文介绍了将Flask API中的JSON数据解析为抖动列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flutter&烧瓶api.我必须从flask api获取数据,然后将其保存到列表中.我是Flutter的入门者,所以请耐心等待!

I'm working on a project using Flutter & Flask api. I have to grab the data from flask api and save into the lists in a flutter. I'm a beginner for Flutter just getting started, so bear with me for this, please!

这是我到目前为止所做的:

Here's what I have done so far:

import 'dart:convert';

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

List<String> images = [
  "assets/image_04.jpg",
  "assets/image_03.jpg",
  "assets/image_02.jpg",
  "assets/image_06.jpg",
];
List<String> title = [];

class Ayah {
  final String text;
  final String translation;
  final String sound;
  final String ref;

  Ayah({this.text, this.translation, this.sound, this.ref});

  factory Ayah.fromJson(Map<String, dynamic> json) {
    return Ayah(
        text: json['text'],
        translation: json['translation'],
        sound: json['sound'],
        ref: json['ref']);
  }
}

// A function that converts a response body into a List<Photo>.
List<Ayah> parseAyahs(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
  List<Ayah> mylist = parsed.map<Ayah>((json) => Ayah.fromJson(json)).toList();
  print('this is here:');
  for (int i = 0; i < parsed.length; i++) {
    print(parsed[i]);
    title.add(parsed[i]['ref']);
  }
  return mylist;
}

Future<List<Ayah>> fetchAyahs(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/photos');

  // return compute(parseAyahs, response.body);
  return parseAyahs(response.body);
}

,这是我要使用此数据的Widget:

and here's the Widget where I want to use this data:

class CardScrollWidget extends StatelessWidget {
  var currentPage;
  var padding = 20.0;
  var verticalInset = 20.0;

  CardScrollWidget(this.currentPage);

  @override
  Widget build(BuildContext context) {
    return new AspectRatio(
      aspectRatio: widgetAspectRatio,
      child: LayoutBuilder(builder: (context, contraints) {
        var width = contraints.maxWidth;
        var height = contraints.maxHeight;

        var safeWidth = width - 2 * padding;
        var safeHeight = height - 2 * padding;

        var heightOfPrimaryCard = safeHeight;
        var widthOfPrimaryCard = heightOfPrimaryCard * cardAspectRatio;

        var primaryCardLeft = safeWidth - widthOfPrimaryCard;
        var horizontalInset = primaryCardLeft / 2;

        List<Widget> cardList = new List();

        for (var i = 0; i < images.length; i++) {
          var delta = i - currentPage;
          bool isOnRight = delta > 0;

          var start = padding +
              max(
                  primaryCardLeft -
                      horizontalInset * -delta * (isOnRight ? 15 : 1),
                  0.0);

          var cardItem = Positioned.directional(
            top: padding + verticalInset * max(-delta, 0.0),
            bottom: padding + verticalInset * max(-delta, 0.0),
            start: start,
            textDirection: TextDirection.rtl,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16.0),
              child: Container(
                decoration: BoxDecoration(color: Colors.white, boxShadow: [
                  BoxShadow(
                      color: Colors.black12,
                      offset: Offset(3.0, 6.0),
                      blurRadius: 10.0)
                ]),
                child: AspectRatio(
                  aspectRatio: cardAspectRatio,
                  child: Stack(
                    fit: StackFit.expand,
                    children: <Widget>[
                      Image.asset(images[i], fit: BoxFit.cover),
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Padding(
                              // padding: EdgeInsets.symmetric(
                              //     horizontal: 16.0, vertical: 18.0),
                              padding: const EdgeInsets.only(
                                  bottom: 60, left: 20, right: 8),
                              child: Text(title[i],
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 25.0,
                                      fontFamily: "SF-Pro-Text-Regular")),
                            ),
                            SizedBox(
                              height: 20.0,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(
                                  left: 22.0, bottom: 72.0),
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                    horizontal: 22.0, vertical: 6.0),
                                decoration: BoxDecoration(
                                    color: Colors.blueAccent,
                                    borderRadius: BorderRadius.circular(20.0)),
                                child: Text("Read Later",
                                    style: TextStyle(color: Colors.white)),
                              ),
                            )
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
          );
          cardList.add(cardItem);
        }
        return Stack(
          children: cardList,
        );
      }),
    );
  }
}

我无法将数据放入title列表. JSON响应在一个数组中有5个JSON对象.

I'm not able to get the data into the title list. The JSON response has 5 JSON objects in an array.

推荐答案

我的场景

当Flutter应用程序需要从烧瓶后端获取数据时,我也有类似的要求.

I also had similar requirement where Flutter app need to fetch data from flask backend.

  1. 后端正在本地计算机上运行
  2. 在外部移动应用中运行的Flutter应用.

主要思想

  • 如果我们要从连接到LAN的其他计算机或设备向API发出HTTP请求,则应使用开发计算机的IP地址0.0.0.0(对于IPv4配置)或::(对于IPv6配置)作为开发服务器所需的IP地址.
  • 如果我们将0.0.0.0指定为IPv4配置所需的IP地址,则开发服务器将在端口5000的每个接口上进行监听.
  • 步骤

    1. 因此在烧瓶后端中添加一个用于调用app.run的主机参数

        if __name__ == '__main__': 
             app.run(host='0.0.0.0', debug=True)
    

    1. 现在,本地网络中的所有设备都可以使用计算机的本地IP对其进行访问.例如:192.168.1.101

    您可以在Windows上使用ipconfig或在Linux/Mac上使用ifconfig检查本地IP

    You can check local IP with ipconfig on Windows or ifconfig on Linux/Mac

    1. 以下是Flutter端的示例get呼叫

    class MovieApiService {
    
      static List<Movie> parseProducts(String responseBody) {
        final parsed = json.decode(responseBody);
        print(parsed);
        return parsed.map<Movie>((json) =>Movie.fromJson(json)).toList();
      }
    
      static Future<List<Movie>> getMovies() async {
        final response = await http.get('http://192.168.1.101:5000/movies');
        if (response.statusCode == 200) {
          return parseProducts(response.body);
        } else {
          return null;
        }
      }
    
    }
    
    

    有关其他参考: https://subscription.packtpub.com/book/application_development/9781789532227/1/ch01lvl1sec23/making-http-requests-to-the-flask-api

    https://www.tutorialspoint.com/flutter/flutter_accessing_rest_api.htm

    这篇关于将Flask API中的JSON数据解析为抖动列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆