Разбираем данные json из api флакона в списки флаттера
Я работаю над проектом с использованием Flutter & Flask api. Мне нужно взять данные из api фляги и сохранить в списках в трепете. Я новичок во Flutter, только начинаю, так что потерпите меня, пожалуйста!
Вот что я сделал до сих пор:
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
где я хочу использовать эти данные:
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 в массиве.
1 ответ
МОЙ СЦЕНАРИЙ
У меня также было аналогичное требование, когда приложение Flutter должно получать данные из бэкэнда фляги.
- Бэкэнд работает на локальном компьютере
- Приложение Flutter работает во внешнем мобильном приложении.
Основная идея
- если мы хотим делать HTTP-запросы к нашему API с других компьютеров или устройств, подключенных к нашей локальной сети, мы должны использовать IP-адрес компьютера разработки, 0.0.0.0 (для конфигураций IPv4) или:: (для конфигураций IPv6) в качестве желаемого IP-адреса. для нашего сервера разработки.
- Если мы укажем 0.0.0.0 в качестве желаемого IP-адреса для конфигураций IPv4, сервер разработки будет прослушивать каждый интерфейс на порту 5000.
Шаги
- Так что добавьте аргумент хоста для вызова app.run в бэкэнде фляги
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
- Теперь все устройства в локальной сети могут получить к нему доступ, используя локальный IP-адрес вашего компьютера. например: 192.168.1.101
Вы можете проверить локальный IP-адрес с помощью ipconfig
в Windows или ifconfig
на Linux/Mac
- Ниже приведен пример вызова с конца Flutter.
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